package cn.picclife.mwx.manager.sys.service.impl;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import cn.picclife.mwx.common.core.util.JsonUtils;
import cn.picclife.mwx.manager.sys.controller.CollectDataController;
import cn.picclife.mwx.manager.sys.model.bo.*;
import cn.picclife.mwx.manager.util.ASUtils;
import cn.picclife.mwx.manager.util.Md5Util1;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import cn.picclife.mwx.manager.sys.mapper.DataCollectMapper;
import cn.picclife.mwx.manager.sys.mapper.SysMaintainHtmlMapper;
import cn.picclife.mwx.manager.sys.mapper.SysMaintainMapper;
import cn.picclife.mwx.manager.sys.mapper.SysMaintainVersionMapper;
import cn.picclife.mwx.manager.sys.mapper.SysMaintainVersionUrlMapper;
import cn.picclife.mwx.manager.sys.mapper.TrackMapper;
import cn.picclife.mwx.manager.sys.model.po.DataCollect;
import cn.picclife.mwx.manager.sys.model.po.DataCollectUser;
import cn.picclife.mwx.manager.sys.model.po.ProjsonObj;
import cn.picclife.mwx.manager.sys.model.po.ProjsonStrObj;
import cn.picclife.mwx.manager.sys.model.po.SysMaintain;
import cn.picclife.mwx.manager.sys.model.po.SysMaintainHtml;
import cn.picclife.mwx.manager.sys.model.po.SysMaintainVersionUrl;
import cn.picclife.mwx.manager.sys.model.po.SysmaintainVersion;
import cn.picclife.mwx.manager.sys.model.po.Track;
import cn.picclife.mwx.manager.sys.model.po.TrackPo;
import cn.picclife.mwx.manager.sys.service.CollectDataService;
import cn.picclife.mwx.manager.sys.service.DownLoadFile;
import cn.picclife.mwx.manager.util.RedisUtil;
import cn.picclife.mwx.manager.util.enums.ResponseStatusEnum;


@Service
public class CollectDataServiceImpl implements CollectDataService{
	
	private static final Log log = LogFactory.getLog(CollectDataServiceImpl.class);
	
	@Value("${branch.secret}")
	private String secret;

	@Value("${file.down.url}")
	private String filePath;
	
	@Value("${file.www.uri}")
	private String filePathUrl;
	
	@Value("${file.requestAddress}")
	private String requestAddress;
	
	@Value("${file.ebankimage}")
	private String ebankimage;
	
	@Value("${sd.flag}")
	private boolean sdflag;

	private static String fengefu="====BehaviorTraceVedioBack====";
	private static String commonzippath="/data/work/appdata/staticdown/mbank/800";
	private static String staticresource="http://36.10.13.81:9000/minio";

	static {
		try {
			Properties prop = new Properties();
			InputStream in = CollectDataServiceImpl.class.getResourceAsStream("/config.properties");
			prop.load(in);
			CollectDataServiceImpl.fengefu=prop.getProperty("upload.fengefu").trim();
			CollectDataServiceImpl.commonzippath=prop.getProperty("commonzippath").trim();
			CollectDataServiceImpl.staticresource=prop.getProperty("staticresource").trim();
			System.out.println("获取配置文件upload属性成功"+"CollectDataServiceImpl");
		} catch (IOException e) {
			System.out.println("CollectDataServiceImpl获取配置文件upload属性失败，使用代码默认的上传属性");
		}
	}


	
	@Resource(name = "redisCache")
	private RedisUtil redisUtil;

	@Autowired
	private DataCollectMapper dataCollectMapper;

	@Autowired
	private SysMaintainMapper sysMaintainMapper;
	
	@Autowired
	private SysMaintainVersionMapper sysMaintainVersionMapper;
	
	@Autowired
	private SysMaintainVersionUrlMapper sysMaintainVersionUrlMapper;
	
	@Autowired
	private SysMaintainHtmlMapper sysMaintainHtmlMapper;

	@Autowired
	private TrackMapper mapper;

	@Autowired
	private DownLoadFile downfile;
	
//	@Autowired
//	private CollectHtmlVideoMapper collectHtmlVideoMapper;
	
	/**
	 * 存储数据功能
	 */
	public void saveData(SaveCollectRequest req) throws Exception{
		DataCollect bo = new DataCollect();
		int saveFlag = 0;//0-未保存成功，1-保存成功
		
		//这里是分割线------------------------------------------------------------
		List<String> reList = req.getLinkArray();
		List<String> recordList = req.getRecordData();//
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String todayStr = sdf.format(new Date());
		String versionkey = "v2"+todayStr + req.getSystemCode() + "Version";//当天日期+系统编码+Version
		//若redis有版本号，则以redis版本号为主，若无，则增加
		String newVersion = ResponseStatusEnum.VERSION.getCode();//v001
		String systemFlagStr = "";
		String systemurl = "";
		SysMaintain sysmaintain = sysMaintainMapper.queryBySystemNo(req.getSystemCode());//查询项目记录
		if(sysmaintain!=null&&sysmaintain.getSystemFlagStr()!=null&&sysmaintain.getSystemUrl()!=null) {
			systemFlagStr = sysmaintain.getSystemFlagStr();//项目标识字符串,可以理解为项目的唯一标识
			systemurl = sysmaintain.getSystemUrl();//项目地址URL
		}
		List<SysmaintainVersion> versionlist = sysMaintainVersionMapper.queryBySystemNo(req.getSystemCode());//查询项目的所有版本信息
		SysmaintainVersion version = null;
		if(versionlist!=null&&versionlist.size()>0) {
			version = versionlist.get(0);//数据库里面项目的最新版本对象信息
		}
		if(version!=null&&version.getVersionNo()!=null&&version.getVersionNo().trim().length()>0) {
			newVersion = version.getVersionNo();//数据库中最新的版本号
		}
		String redisVersion = redisUtil.getStr(versionkey);//获取redis中存储最新的版本号
		if(redisVersion!=null&&redisVersion.trim().length()>0) {
			newVersion = redisVersion;//redis有最新的版本号，以redis的版本号为主
		}
		//处理山东城商行版本begin
		if(sdflag){		log.info("zip包静态资源下载sdflag" +sdflag );
		}
//		log.info("zip包静态资源下载sdflag" +sdflag );
		if(req.getVersion()!=null&&req.getVersion().trim().length()>0){
			log.info("zip包静态资源下载"+req.getVersion());
		}
		if(sdflag&&req.getVersion()!=null&&req.getVersion().trim().length()>0) {
			newVersion = req.getVersion();//山东的版本号以req前台传的为主
			//异步下载下载解压静态资源
			log.info("zip包静态资源下载service开始");
			downfile.asyncDown(req);
			log.info("zip包静态资源下载service结束");
		}
		//处理ABC版本end
		String filederpath = filePathUrl + req.getSystemCode() + "/" + newVersion + "/";//https://www.bjnfbk.com/systembak02/NrrWeb/  这个是内网访问地址=====
		/* 获取所有需要下载的文件路径 */
		log.info("获取路径数量:" + reList.size());
		for (int i = 0; i < reList.size(); i++) {
			//http://36.30.78.166:8802/vendor.css
				String url = reList.get(i);//前端传的是公网路径吗-----------
				String startUrl = url;//
				//处理ABC数据 begin
				String staticURL = url;
				/*if("ABC".equals(req.getSystemCode())&&url.indexOf("/CommonWeb")>-1) {
					int num = url.indexOf("/CommonWeb");
					url = staticUrl + url.substring(num);
				}*/
				if(sdflag&&systemFlagStr.trim().length()>0
						&&systemurl.trim().length()>0&&url.indexOf(systemFlagStr)>-1) {
					int num = url.indexOf(systemFlagStr);
					url = (systemurl +"/"+ url.substring(num));
				}
				//处理ABC数据 end
				if (!url.contains("/api/commom/image/querypicture") && url.indexOf("?")>-1 ) {
					url = url.substring(0, url.indexOf("?"));//==============url http://36.30.78.166:8802/vendor.css
				}
				String urlTemp = "";
				if(-1 == url.indexOf("//")){
					urlTemp = url;
				}else{
					urlTemp = url.substring(url.indexOf("//")+2);//去除http://  ======             36.30.78.166:8802/vendor.css
				}
				if (url.contains("/api/commom/image/querypicture")) {
				//地址需要将？和 = 替换成/
				url=url.replaceAll("[?,=]", "_");
			}
				// 获取文件全路径
				String fileName = url;
				// 获取文件名
				String filepath1 = "";
			/**
			 * 逻辑：
			 * 		连接含6.0Web的一定替换不用自己添加6.0web
			 * 		不含6.0web但是zip解压的，自己添加6.0web
			 * 		下载的无需添加6.0Web
			 */
			if(urlTemp.indexOf("/") == urlTemp.lastIndexOf("/")){//资源访问链接只有1个/
					log.info("urlTemp的url"+urlTemp+"  ,包含"+systemFlagStr+"吗"+(urlTemp.indexOf(systemFlagStr)>-1));
					if(sdflag&&systemFlagStr.trim().length()>0
							&&systemurl.trim().length()>0&&urlTemp.indexOf(systemFlagStr)>-1){
						filepath1 = filederpath + urlTemp.substring(urlTemp.indexOf("/") + 1);
						log.info("urlTemp的url"+urlTemp+" 包含"+systemFlagStr);
					}else if(!urlTemp.contains("static/public")){
						filepath1 = filederpath +"6.0Web/"+ urlTemp.substring(urlTemp.indexOf("/") + 1);
						log.info("urlTemp的url"+urlTemp+" 不包含"+systemFlagStr);
					}else{
						filepath1 = filederpath + urlTemp.substring(urlTemp.indexOf("/") + 1);
						log.info("urlTemp的url"+"需要内网下载的"+urlTemp+urlTemp+"需要内网下载的");
					}
				}else{
					log.info("urlTemp的urlllll"+urlTemp+"  ,包含"+systemFlagStr+"吗"+(urlTemp.indexOf(systemFlagStr)>-1));
					if(sdflag&&systemFlagStr.trim().length()>0
							&&systemurl.trim().length()>0&&urlTemp.indexOf(systemFlagStr)>-1){
						filepath1 = filederpath + urlTemp.substring(urlTemp.indexOf("/") + 1, urlTemp.lastIndexOf("/") + 1);
						log.info("urlTemp的urlllll"+urlTemp+" 包含"+systemFlagStr);
					}else if(!urlTemp.contains("static/public")){
						filepath1 = filederpath +"6.0Web/"+ urlTemp.substring(urlTemp.indexOf("/") + 1, urlTemp.lastIndexOf("/") + 1);
						log.info("urlTemp的urlllll"+urlTemp+" 不包含"+systemFlagStr);
					}else{
						filepath1 = filederpath + urlTemp.substring(urlTemp.indexOf("/") + 1, urlTemp.lastIndexOf("/") + 1);
						log.info("urlTemp的urlllll"+"需要内网下载的"+urlTemp);
					}

				}
				fileName = fileName.substring(fileName.lastIndexOf("/") + 1);
				log.info(":" + reList.size());
				//==============================================山东条款协议20210108特殊处理=======================
				if(url.contains("/image/instructions/")&&sdflag){
					log.info("条款协议特殊处理开始" );
					//获取new文件夹的MD5值
					//this.compareVersion(null, sdxyurl);
					String urlinstruc=url;
					urlinstruc=ebankimage+urlinstruc.substring(urlinstruc.indexOf("/image/instructions/"),urlinstruc.length());
					SysMaintainVersionUrl sysMaintainVersionUrl = this.compareVersion(null, urlinstruc);
					String md5 = sysMaintainVersionUrl.getLastModified();
					md5=md5.replaceAll("\\s*", "");
					log.info("LastModified： "+md5 );
					filepath1=filepath1+md5+"/";
					log.info("条款协议特殊处理结束" );
				}

				//==============================================山东条款协议20210108特殊处理=======================

				String newFileP = filepath1 + fileName;
				List<String> recordListNew = new ArrayList<String>();
				for(int k = 0; k < recordList.size(); k++){//前端传的视频的json数组
					String json = "";
					if (startUrl.indexOf("?")>-1) {
					    json = recordList.get(k).replace(startUrl, newFileP);//将视频中的公网资源换成内网资源
					}else {
						json = recordList.get(k).replaceAll(startUrl, newFileP);
					}
					//String json = recordList.get(k).replaceAll(startUrl, newFileP);
					//处理ABC数据 begin
					if(sdflag&&systemFlagStr.trim().length()>0&&url.indexOf(systemFlagStr)>-1) {
						json = recordList.get(k).replaceAll(staticURL, newFileP);
					}
					//处理ABC数据 end
					recordListNew.add(json);
				}
				recordList = recordListNew;
		}
		//downfile.downLoadFile(req.getLinkArray(), filederpath, req.getUuid(), recordList, req.getStartTime());
		//req.setRecordData(recordList);
		//暂时连不上
		
//		redisUtil.saveZset(req.getUuid(), recordList, req.getTimestamp());
		/*log.info("保存成功");
		Set<String> strSet = redisUtil.getZset(req.getUuid());
		Iterator<String> ite = strSet.iterator();
		List<String> retList = new ArrayList<String>();
		while(ite.hasNext()){
			String obj =  ite.next();
			retList.add(obj);
		}
		log.info("从redis重取出的集合是：" + retList);*/
		// 这里是分割线------------------------------------------------------------
		/*SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		Date date = new Date();
		String nowDateStr = sdf.format(date);
		// 文件路径 D:\wenjian
		String filePath = ResponseStatusEnum.FILE_URL.getName(); //"D:\\wenjian\\"
		filePath = filePath+nowDateStr.substring(0,4)+"/"+nowDateStr.substring(4,6)+"/"+nowDateStr.substring(6,8)+"/"+req.getUuid()+"/";//在文件路径下新增文件以uuid为名
		File file = new File(filePath);
		
        //如果文件夹不存在则新建
        if(!file.exists()) {
        	file.mkdirs();
        }
		
		String fileName = req.getUuid() + nowDateStr + ".txt";// 
		String path = filesPath + fileName;*/
		bo.setId(req.getUuid());
		bo.setUploadTime(new Date());
		//bo.setUploadUrl(path);
		bo.setAuditState("0");
		bo.setVersionNo(req.getVersion());//版本号
		Calendar c = Calendar.getInstance();
		c.setTimeInMillis(req.getStartTime());
		bo.setStartTime(c.getTime());//播放起期
		log.info("yzxtime----开始时间==============================="+req.getStartTime());
		if(0 != req.getEndTime()){
			c.setTimeInMillis(req.getEndTime());
			bo.setEndTime(c.getTime());//播放止期
			log.info("yzxtime-----结束时间==============================="+req.getStartTime());
		}
		bo.setProductCode(req.getProductCode());//产品编码
		bo.setPluginName(req.getPluginName());//插件名称
		bo.setPluginVersion(req.getPluginVersion());//插件版本
		bo.setSysCode(req.getSystemCode());//系统编码
		if("1".equals(req.getIsPC())){
			bo.setIsPc(req.getIsPC());
		}
		/*List<String> list = req.getRecordData();
		StringBuffer data = new StringBuffer();
		for(String str:list) {
			data.append(str).append("\n");
		}*/
		
		DataCollect dataCollect = dataCollectMapper.queryDataById(req.getUuid());
		log.info("=========数据录制采集接口查询uuid数据："+JSONObject.toJSON(dataCollect));
		//若该uuid已存在，说明已生成数据文件，需要更新文件数据
		if(null!=dataCollect&&null!=dataCollect.getId()&&dataCollect.getId().trim().length()>0) {
			dataCollectMapper.updateDataById(bo);
			//updateFile(dataCollect.getUploadUrl(),data.toString());
		}else {
			//createFile(path,data.toString());
			dataCollectMapper.saveData(bo);
		}
		
		redisUtil.saveZset("v2"+"video"+req.getUuid(), recordList, req.getTimestamp());//string ,list,时间戳
		/*//分段视频开始
		List<SysMaintainHtml> htmlList = sysMaintainHtmlMapper.queryBySysCode(req.getSystemCode());
		if(req.getHtmlArray()==null||req.getHtmlArray().size()<=0||htmlList==null||htmlList.size()<=0) {
			return ;
		}
		String htmlId = "";
		//TODO 入参页面是否是集合 begin
		for(HtmlData data:req.getHtmlArray()) {
			if(data==null||data.getUrl()==null||data.getUrl().trim().length()<=0) {
				continue;
			}
			for(SysMaintainHtml html :htmlList) {
				if(html==null) {
					continue;
				}
				if(data.getUrl().equals(html.getFileUrl())) {
					htmlId = html.getId();
					break;
				}
			}
		}
		//TODO 入参页面是否是集合 end
		if("".equals(htmlId.trim().length()<=0)) {
			return;
		}
		CollectHtmlVideo collectVideo = collectHtmlVideoMapper.queryByCollectHtmlId(req.getUuid(), htmlId);
		String id = UUID.randomUUID().toString();
		if(collectVideo!=null&&collectVideo.getId()!=null&&collectVideo.getId().trim().length()>0) {
			id = collectVideo.getId();
		}else {
			CollectHtmlVideo htmlvideo = new CollectHtmlVideo();
			htmlvideo.setDatacollectId(req.getUuid());
			htmlvideo.setHtmlId(htmlId);
			htmlvideo.setId(id);
			htmlvideo.setUploadtime(new Date());
			collectHtmlVideoMapper.saveHtmlVideo(htmlvideo);
		}
		redisUtil.saveZset("htmlvideo"+id, recordList, req.getTimestamp());*/
	}
	
	
	
	public String getVersionNo(String oldVersion){
		
		String newVersion = "";
		String num = oldVersion.substring(1);
		int vernum = Integer.parseInt(num);
		String numstr = (vernum+1)+"";
		while(numstr.length()<(oldVersion.length()-1)) {
			numstr = "0"+numstr;
		}
		return oldVersion.substring(0,1)+numstr;//V001
	}
	
	
	

	/**
	 * 对比html文件是否被修改
	 * @param versionurl
	 * @param htmlurl
	 * @return
	 */
	public SysMaintainVersionUrl compareVersion(SysMaintainVersionUrl versionurl,String htmlurl) {

		if(htmlurl==null||htmlurl.trim().length()<=0) {
			return null;
		}
		URL url = null;
		URLConnection conn = null;
		
		String etag = "";
		String lastModified = "";
		try {
			url = new URL(htmlurl);

			conn = url.openConnection();
			conn.setConnectTimeout(3000);
			Map headers = conn.getHeaderFields();
			Set<String> keys = headers.keySet();
			for (String key : keys) {
				if("ETag".equals(key)) {
					etag = conn.getHeaderField(key);
				}
				if("Last-Modified".equals(key)) {
					lastModified = conn.getHeaderField(key);
				}
			}
			
		} catch (Exception e) {
			//e.printStackTrace();
		}
		if(versionurl==null||versionurl.getSysversionId()==null||versionurl.getSysversionId().trim().length()<=0) {
			versionurl = new SysMaintainVersionUrl();
		}
		//if(etag==null || etag.trim().length()<=0 || lastModified==null || lastModified.trim().length()<=0) {
	//		return null;
		//}
		if(versionurl.getLastModified()==null) {
			versionurl.setLastModified("");
		}
		if(lastModified==null) {
			lastModified="";
		}
		//html响应头信息一致
		if(versionurl!=null&&etag.equals(versionurl.geteTag())&&lastModified.equals(versionurl.getLastModified())) {
			return null;
		}
		versionurl.seteTag(etag);
		versionurl.setLastModified(lastModified);
		
		return versionurl;
	}
	/**
	 * 更新数据表t_data_collect信息
	 */
	public int updateData(UpdateCollectReq req) throws Exception {

		log.info("------collectDataServiceImpl-----updateData----req-----"+JsonUtils.ObjectToJson(req));
		
		int updateFlag = 0;
		DataCollect dataCollect = new DataCollect();
		log.info("------collectDataServiceImpl-----updateData----req-----"+req.getId());
		if(null != req.getId() && !"".equals(req.getId().trim())) {
			log.info("------collectDataServiceImpl-----updateData----req-----查询出毛病没");
			dataCollect = dataCollectMapper.queryDataById(req.getId());
			log.info("------collectDataServiceImpl-----updateData----req-----查询出毛病了呀");
		}		
		//判断queryid
		if(null != req.getQuery_id() && !"".equals(req.getQuery_id().trim())) {
			dataCollect = dataCollectMapper.queryDataByQueryId(req.getQuery_id());
		}
		if(null==dataCollect) {
			log.info("------collectDataServiceImpl-----updateData----req-----没接入系统");//这儿为啥有null可能性，那是因为有可能查不到
			return updateFlag;						
		}
        log.info("------collectDataServiceImpl-----updateData----req-----接入了系统");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		DataCollect bo = new DataCollect();
		bo.setId(dataCollect.getId());//数据主键id
		bo.setBusinessNo(req.getBusinessNo());//业务识别号（保单号）
		bo.setPhoneModel(req.getPhoneModel());//手机型号
		bo.setSysCode(req.getSysCode());//系统名称
		bo.setAppliName(req.getAppliName());//投保人姓名
		bo.setAppliBirthday(req.getAppliBirthday());//投保人出生日期
		bo.setAppliCardNo(req.getAppliCardNo());//投保人证件号
		bo.setInsuredName(req.getInsuredName());//被保人姓名
		bo.setInsuredBirthday(req.getInsuredBirthday());//被保人出生日期
		bo.setInsuredCardNo(req.getInsuredCardNo());//被保人证件号
		bo.setProductName(req.getProductName());//产品名称
		bo.setProductCode(req.getProductCode());//产品编码
		bo.setTotalPremium(req.getTotalPremium());//总保费
		bo.setPolicyStatus(req.getPolicyStatus());//保单状态
		bo.setAuditState(req.getAuditState());//审核状态：0-未审核、1-审核已通过、2-审核未通过\3-审核中
		bo.setOrganCode(req.getOrganCode());//机构
		bo.setPolicyNo(req.getPolicyNo());
		bo.setEquipmentId(req.getEquipmentId());
		bo.setExceptionId(req.getExceptionId());
		bo.setPhoneNumber(req.getPhoneNumber());

		//设置projson 只增加
		String projson = "";//projson主要含义
		if(dataCollect.getProjson()==null||dataCollect.getProjson().trim().length()<-1) {
			projson=req.getProjson();//如果数据库中此数据是null的话，以前端传的字段为准
		}
		if(req.getProjson()!=null&&req.getProjson().trim().length()>0&&
				dataCollect.getProjson()!=null&&dataCollect.getProjson().trim().length()>0) {//此处逻辑数据库中projson！null且前端req传入projson，合并projson
																							 //放入旧对象中
			//之前的数据
			ProjsonObj obj = JSON.parseObject(dataCollect.getProjson(), ProjsonObj.class);
			//最新数据
			ProjsonObj newobj = JSON.parseObject(req.getProjson(), ProjsonObj.class);
			if(obj.getProjson()!=null&&obj.getProjson().size()>0) {
				List<ProjsonStrObj> list = obj.getProjson();
				List<ProjsonStrObj> list1 = new ArrayList<ProjsonStrObj>();
				for(ProjsonStrObj newstr:list) {
					list1.add(newstr);
				}
				if(newobj.getProjson()!=null&&newobj.getProjson().size()>0) {
					List<ProjsonStrObj> listnew = obj.getProjson();
					for(ProjsonStrObj newobjstr:listnew) {
						list1.add(newobjstr);
					}
				}
				obj.setProjson(list1);
				projson = JSONObject.toJSON(obj).toString();
			}
		}
		//设置projson 只增加
		bo.setProjson(projson);//json串
		bo.setDispute_recourse(req.getDispute_recourse());//纠纷原因
		bo.setFriend_status(req.getFriend_status());//纠纷状态
		if(null!=req.getDispute_start()&&req.getDispute_start().trim().length()>0) {
			bo.setDispute_start(sdf.parse(req.getDispute_start()));//纠纷开始时间
		}
		if(null!=req.getDispute_end()&&req.getDispute_end().trim().length()>0) {
			bo.setDispute_end(sdf.parse(req.getDispute_end()));//纠纷结束时间
		}
		bo.setVersionNo(req.getVersionNo());//版本号
		bo.setDataState(req.getDataState());
		bo.setInsurancePeriod(req.getInsurancePeriod());
		SysMaintain maintain = new SysMaintain();
		maintain.setSystemNo(req.getSysCode());
		List<SysMaintain>mainList = sysMaintainMapper.querySysMaintain(maintain);
		if(mainList==null||mainList.size()<=0) {
			log.info("====视频采集更新接口==未查询到系统信息==无法维护该系统版本=");
			return updateFlag;
		}
		log.info("req---此版本存在---");
		updateFlag = dataCollectMapper.updateDataById(bo);
		log.info("========updateFlag========"+updateFlag);
		return updateFlag;
	}

	/**
	 * 上传TXT
	 * @param buffer
	 * @param req
	 */
	@Override
	public int uploadTxt(String buffer, UpdateCollectReq req)  {
		int uploadFlag=0;
		List<String> failIdList=new ArrayList<>();
		//===========作为分隔符
		//save操作
		String[] split = buffer.split(fengefu);
		if (split==null||split.length==0) {
			log.info("collectDataServiceImpl---uploadTxt--方法----文件上传的txt是个空的txt");
			uploadFlag=-1;
			deleteFailData(failIdList);
			return uploadFlag;
		}
		for (String json : split) {
			log.info("------CollectDataService-----uploadTxt-----decrypt----开始 ");
			DecrySaveReq decrySaveReq = JsonUtils.json2Obj(json, DecrySaveReq.class);
			log.info("------CollectDataService-----uploadTxt-----decrypt----结束 ");
			SaveCollectRequest saveCollectRequest = new SaveCollectRequest();
			try {
				saveCollectRequest = decrySaveReq.getUpdateStr();
//				String decrypt= ASUtils.decrypt(updateStr,asekey,ResponseStatusEnum.AES_KEY.getName());
//				log.info("------CollectDataService-----uploadTxt-----txt里面解密成功： "+updateStr);
//				saveCollectRequest = JsonUtils.json2Obj(updateStr, SaveCollectRequest.class);
//				log.info("------CollectDataService-----uploadTxt-----decrypt----对象成功： ");
				saveData(saveCollectRequest);

			} catch (Exception e) {
				log.info("Txt文件上传的时候，saveData接口异常");
				uploadFlag=-1;
				failIdList.add(saveCollectRequest.getUuid());
				deleteFailData(failIdList);
				return uploadFlag;
			}
		}
		//更新操作
		try {
			uploadFlag = updateData(req);
		} catch (Exception e) {
			log.info("Txt文件上传的时候，updateData接口异常");
			uploadFlag=-2;
			/*failIdList.add(req.getId());
			deleteFailData(failIdList);*/
			return uploadFlag;
		}
		return uploadFlag;
	}

	/**
	 * 上传zip包
	 * @param files txt结合
	 * @param req update集合，自己组装
	 * @param path zip的解压目录
	 * @param filePath zip的暂存目录
	 * @param uuidStringList uuid的集合
	 * @param aseString upade参数json串
	 * @return
	 */
	@Override
//	public int uploadZip(String s, List<UpdateCollectReq> req, String path, String filePath) {
	public int uploadZip(List<File> files, List<UpdateCollectReq> req, String path, String filePath,List<String> uuidStringList,String aseString) {
		int flag = 0;
		if (files.size()==0) {
			log.info("allZip中上传的zip包中没有txt文件");
			return 1;
		}
		List<String> uuidList = new ArrayList<>();
		//files里面全都是TXT文件
		for (File file1 : files) {
			String txt2String = txt2String(file1);
			String[] split = txt2String.split(fengefu);
			for (int i = 0; i < split.length; i++) {
				DecrySaveReq decrySaveReq = JsonUtils.json2Obj(split[i], DecrySaveReq.class);
				String decrypt= "";
				SaveCollectRequest saveCollectRequest  = decrySaveReq.getUpdateStr();
				if(saveCollectRequest==null){
					log.info("allZip中savejson数据转换失败");
					if (uuidList.size()>0) {
						deleteFailData(uuidList);
						log.info("allZip中save失败，开始回退，删除redis、txt、数据库相关数据，失败原因savejson数据转换失败");
					}
                    return 4;
				}
				log.info("---allZip---CollectDataService-----uploadZip-----decrypt----对象成功： ");
				if(i==0&&saveCollectRequest!=null){
					uuidList.add(saveCollectRequest.getUuid());
				}
				try {
					saveData(saveCollectRequest);
				} catch (Exception e) {
					log.info("allZip中save失败，开始回退，删除redis、txt、数据库相关数据，失败原因save接口出现Exception");
					if (uuidList.size()>0) {
						deleteFailData(uuidList);
					}
					return 5;
				}
			}
		}
		/**
		 * save执行成功后执行update操作
		 * =====>(1)解析aseString,自己组装List<UpdateCollectReq> req更新数据的集合---->将aseString变成java对象，利用uuidStringList组成List<UpdateCollectReq> req
		 */

		//List<UpdateCollectReq> req = JSONObject.parseArray(reqJson, UpdateCollectReq.class);
		for (String id1 : uuidStringList) {
			UpdateCollectReq req1 = JSON.parseObject(aseString, UpdateCollectReq.class);
//			String objectToJson = JsonUtils.ObjectToJson(req1);
//			log.info("allZip中的aseString的json值为"+objectToJson);
			if (req1==null) {
				//update的传参不能转成java对象
				log.info("allZip中update的传参不能转成java对象");
				if (uuidList.size()>0) {
					deleteFailData(uuidList);
				}
				return 8;
			}
			req1.setId(id1);
			req.add(req1);
		}
		log.info("allZip中组装List<UpdateCollectReq> req完成");
		for (UpdateCollectReq updateCollectReq : req) {
			try {
				int updateData = updateData(updateCollectReq);
				if(updateData ==0){
					log.info("allZip上传updateData的数据库没更新成功");
					if (uuidList.size()>0) {
						deleteFailData(uuidList);
					}
					return 6;
				}
			} catch (Exception e) {
				log.info("allZip包的update接口出现异常，此次上传zip包失败");
				if (uuidList.size()>0) {
					deleteFailData(uuidList);
				}
				return 7;
			}
		}

		log.info("allZip包的update逻辑顺利");
		//上传成功，更新成功，删除uuid文件夹
		deleteAll(new File(path));
		deleteAll(new File(filePath));
		return 0;
	}

	/**
	 * zip包数据库回退策略
	 * @param uuidList
	 */
	public void deleteZipFail(List<String> uuidList){
        if (uuidList.size()>0) {
            dataCollectMapper.deleteZipFail(uuidList);
        }
    }

	/**
	 * 删除文件及子文件
	 * @param file
	 * @return
	 */
	//封装一个方法：用来实现文件夹的删除，返回一个布尔值，判断是否删除成功
	public static boolean deleteAll(File file){

		int count=0;
		//1.拿到文件后，第一步判断是否为空或不存在
		if (file==null || !file.exists()){
			System.out.println("文件不存在");
			return false;
		}
		//2.调用File的listFiles方法拿到目录下所有的文件对象
		File[] files = file.listFiles();
		//3.遍历文件对象数组
		for (File f:files) {
			//4.判断文件对象是不是目录
			if (f.isDirectory()){
				System.out.println(f.getName());
				//5.如果是目录，就递归
				deleteAll(f);
			}else{
				System.out.println(f.getName());
				System.gc();
				f.delete();

			}
		}
		//7.前面的遍历已经把TEST目录下所有文件都删除了
		//delete方法只有在file是空目录的前提下，才能成功删除
		file.delete();
		return true;
	}


	/**
	 * TXT文件变为String内容
	 * @param file
	 * @return
	 */
	public static String txt2String(File file){
		StringBuilder result = new StringBuilder();
		try{
			// 构造一个BufferedReader类来读取文件
			BufferedReader br = new BufferedReader(new FileReader(file));
			String s = null;
			// 使用readLine方法，一次读一行
			while((s = br.readLine())!=null){
				result.append(System.lineSeparator()+s);
			}
			br.close();
		}catch(Exception e){
			e.printStackTrace();
		}
		return result.toString();
	}

	/**
	 * 获取视频回放信息
	 */
	public List<String> queryDataFile(UpdateCollectReq req) throws Exception {
		
		DataCollect bo = new DataCollect();
		bo.setId(req.getId());//数据主键id
		bo.setBusinessNo(req.getBusinessNo());//业务识别号（保单号）
		List<DataCollect> dataCollectList = dataCollectMapper.queryData(bo);
		log.info("======queryDataFile视频回放接口数据查询结果:======"+JSONObject.toJSONString(dataCollectList).toString());
		if(null==dataCollectList||dataCollectList.size()<=0) {
			return null;
		}
		DataCollect dataCollect = dataCollectList.get(0);
		if(null==dataCollect||null==dataCollect.getUploadUrl()||dataCollect.getUploadUrl().trim().length()<=0) {
			return null;
		}
		//return readData(dataCollect.getUploadUrl());
		if("1".equals(dataCollect.getArchiveFlag())) {
			return readData(dataCollect.getArchiveUrl());
		}else {
			return readData(dataCollect.getUploadUrl());
		}

	}
	
	/**
	 * 获取视频播放用户列表
	 */
	public List<DataCollectUser> queryUserList(String datacollectId,HttpServletRequest request){
		
		List<DataCollectUser>userList =  dataCollectMapper.queryDataCollectUser(datacollectId);
		UserSessionBo user = (UserSessionBo) request.getSession().getAttribute("user");
		log.info("==========user:"+user);
		if(null!=user&&null!=user.getOptNo()) {
			DataCollectUser dataUser = new DataCollectUser();
			dataUser.setDatacollectId(datacollectId);
			dataUser.setOptNo(user.getOptNo());
			dataUser.setDeptNo(user.getDeptNo());
			dataUser.setDeptName(user.getDeptName());
			dataUser.setDeptLevel(user.getDeptLevel());
			dataUser.setOptTime(new Date());
			int a = dataCollectMapper.saveDataCollectUser(dataUser);
			log.info("a======"+a);
		}
		return userList;
	}
	
	
	/**
	 * 获取视频回放列表
	 */
	public PageCount queryDataList(UpdateCollectReq req,String deptNo) {
		
		PageCount pageCount = new PageCount();
		pageCount.setNowPage(req.getNowPage());//当前页
		pageCount.setRowNum(req.getRowNum());//每页多少条
		//查询总条数
		Map<String,Object> datemap = new HashMap<String,Object>();
		if(secret.equals("true")){
			datemap.put("deptNo", deptNo);//用户机构
		}
		datemap.put("organCode", req.getOrganCode());//机构代码
		datemap.put("projson", req.getProjson());//业务数据
		log.info("---------projson:"+req.getProjson());
		datemap.put("id", req.getId());//ID
		datemap.put("flag",req.getFlag());
		log.info("---------flag:"+req.getFlag());
		//========================================增加新的搜索条件========================20201210
		//=============二期新增===================================================================
		datemap.put("sysCode",req.getSysCode());
		datemap.put("equipmentId",req.getEquipmentId());
		datemap.put("exceptionId",req.getExceptionId());
		datemap.put("phoneNumber",req.getPhoneNumber());
		//==============================================================================

		
		//总数
		int allCount = dataCollectMapper.queryCountByBunoAppName(datemap);
		log.info("---------总数:"+allCount);
		if(0==pageCount.getRowNum()) {
			pageCount.setRowNum(10);
		}
		if(0==pageCount.getNowPage()) {
			pageCount.setNowPage(1);
		}
		int allPages = allCount / pageCount.getRowNum();

		if (allCount % pageCount.getRowNum() > 0) {
			allPages += 1;//总页数
		}
		pageCount.setAllPages(allPages);
		pageCount.setAllCount(allCount);
		int minTotal = (pageCount.getNowPage() - 1) * pageCount.getRowNum();
		int maxTotal = pageCount.getNowPage() * pageCount.getRowNum();
		pageCount.setMinTotal(minTotal);
		pageCount.setMaxTotal(maxTotal);
		pageCount.setMaxminTotal(maxTotal-minTotal);
		pageCount.setObject(datemap);
		log.info("查询sql的参数："+JSONObject.toJSONString(datemap));
		List<DataCollect> resList = dataCollectMapper.queryDataPageByBunoAppName(pageCount);
		if (resList!=null) {
			for (int i = 0; i <resList.size() ; i++) {
				log.info("查询结果数据"+i+" :"+JSONObject.toJSONString(resList.get(i)));
			}
		}

		pageCount.setDatas(resList);
		return pageCount;
	}

	/**
	 * 更新文件信息
	 * @param url 文件路径
	 * @param data 加载的数据
	 * @throws Exception
	 */
	public void updateFile(String url,String data) throws Exception {
		
		RandomAccessFile rf = null;		
		try {
			rf=new RandomAccessFile(url,"rw");
			rf.seek(rf.length());//将指针移动到文件末尾 
			byte[] datas = data.getBytes("utf-8");//处理中文乱码
			rf.write(datas);
			rf.close();//关闭文件流
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.info("====数据保存接口===更新文件失败=========");
			log.error(e);
			throw e;
		}finally {
			if(null!=rf) {
				rf.close();//关闭文件流
			}
		}
	}
	
	/**
	 * 创建数据文件
	 * @param url 文件路径
	 * @param data
	 * @throws Exception 
	 */
	public void createFile(String url,String data) throws Exception{
		
		// 写入文件内
		FileOutputStream fos = null;
		File file = null;
		String byteType = "utf-8";
		/*if(url.indexOf(".txt")>-1) {
			byteType = "gb2312";
		}*/
		log.info("文件生成路径及文件名：" + url);
		try {
			file = new File(url);
			fos = new FileOutputStream(file);
			
			byte[] datas = data.toString().getBytes(byteType);
			fos.write(datas);
			fos.flush();
			fos.close();
		} catch (Exception e) {
			log.info("====数据保存接口===创建文件失败=========");
			log.error(e);
		} finally {
			if (null != fos) {
				fos.close();
			}
		}
	}
	
	/**
	 * 获取文件内容
	 * @return
	 * @throws Exception
	 */
	public List<String> readData(String url) throws Exception {
		
		List<String> strList = new ArrayList<String>();
		if(url==null||url.trim().length()<=0) {
			return null;
		}
		File file = new File(url);
		if(!file.exists()) {
			return null;
		}
		FileInputStream fis = null;
		InputStreamReader isr = null ;
		BufferedReader br = null ;
		try {
			fis = new FileInputStream(url);
			// 防止路径乱码  eclipse里创建的txt 用gb2312
			isr = new InputStreamReader(fis, "utf-8");
			br = new BufferedReader(isr);
			String line = "";
		    while ((line = br.readLine()) != null) {
		    	log.info(line);
		    	strList.add(line);
		    }
		    br.close();
		    isr.close();
		    fis.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.error(e);
		}finally {
			if(null!=br) {
				br.close();
			}
			if(null!=isr) {
				isr.close();
			}
			if(null!=fis) {
				fis.close();
			}
		}
		return strList;
	}

	@Override
	public DataResponse insertTrack(TrackBo bo) throws Exception {
		DataResponse response = new DataResponse();
		if(bo == null){
			response.setCode(ResponseStatusEnum.PARAM_IS_NULL.getCode());
			response.setMsg(ResponseStatusEnum.PARAM_IS_NULL.getName());
			return response;
		}
		if(bo.getCollectId() == null || "".equals(bo.getCollectId().trim())){
			response.setCode(ResponseStatusEnum.FAIL_CODE.getCode());
			response.setMsg(ResponseStatusEnum.FAIL_CODE.getName() + "：CollectId不能为空");
			return response;
		}
//		if(bo.getTrackThing() == null || "".equals(bo.getTrackThing().trim())){
//			response.setCode(ResponseStatusEnum.FAIL_CODE.getCode());
//			response.setMsg(ResponseStatusEnum.FAIL_CODE.getName() + "：TrackThing不能为空");
//			return response;
//		}
		if(bo.getWhenTime() == null || "".equals(bo.getWhenTime().trim())){
			response.setCode(ResponseStatusEnum.FAIL_CODE.getCode());
			response.setMsg(ResponseStatusEnum.FAIL_CODE.getName() + "：WhenTime不能为空");
			return response;
		}
		if(bo.getTrackTodo() == null || "".equals(bo.getTrackTodo().trim())){
			response.setCode(ResponseStatusEnum.FAIL_CODE.getCode());
			response.setMsg(ResponseStatusEnum.FAIL_CODE.getName() + "：TrackTodo不能为空");
			return response;
		}
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Track track = new Track();
		track.setId(UUID.randomUUID().toString().replace("-", ""));
		track.setCollectId(bo.getCollectId());
		track.setTrackThing(bo.getTrackThing());
		track.setTrackTodo(bo.getTrackTodo());
		track.setWhenTime(sdf.parse(bo.getWhenTime()));
		track.setTrackTime(new Date());
		try {
			mapper.saveData(track);
			response.setCode(ResponseStatusEnum.SUCCESS_CODE.getCode());
			response.setMsg(ResponseStatusEnum.SUCCESS_CODE.getName());
		} catch (Exception e) {
			log.error(e);
			response.setCode(ResponseStatusEnum.EXCEPTION.getCode());
			response.setMsg(ResponseStatusEnum.EXCEPTION.getName() + "；" + e.getMessage());
		}
		return response;
	}

	@Override
	public DataResponse queryTrackByCollectId(TrackBo bo) throws Exception {
		DataResponse msg = new DataResponse();
		Track tack = new Track();
		if(bo.getCollectId() == null || "".equals(bo.getCollectId().trim())){
			msg.setCode(ResponseStatusEnum.FAIL_CODE.getCode());
			msg.setMsg(ResponseStatusEnum.FAIL_CODE.getName() + "：collectId不能为空");
			return msg;
		}
		tack.setCollectId(bo.getCollectId());
		List<TrackPo> list = mapper.queryDataById(tack);
		for(TrackPo t :list) {
			String whenTime = t.getWhenTime().substring(0,t.getWhenTime().length()-2);
			String trackTime = t.getTrackTime().substring(0,t.getTrackTime().length()-2);
			t.setTrackTime(trackTime);
			t.setWhenTime(whenTime);
		}
		msg.setMsg(ResponseStatusEnum.SUCCESS_CODE.getName());
		msg.setCode(ResponseStatusEnum.SUCCESS_CODE.getCode());
		msg.setData(list);
		return msg;
	}
	
	/**
	 * 完成录制功能
	 * @throws ParseException
	 */
	public DataResponse finishRecord(SaveCollectRequest req) throws Exception {
		
		DataResponse dataResponse = new DataResponse();
		dataResponse.setCode(ResponseStatusEnum.SUCCESS_CODE.getCode());
		dataResponse.setMsg(ResponseStatusEnum.SUCCESS_CODE.getName());
		DataCollect bo = new DataCollect();
		bo.setId(req.getUuid());//数据主键id
		bo.setBusinessNo(req.getBusinessNo());//业务识别号（保单号）
		List<DataCollect> dataCollectList = dataCollectMapper.queryData(bo);
		log.info("======完成录制功能==数据查询结果:======"+JSONObject.toJSONString(dataCollectList).toString());
		if(null==dataCollectList||dataCollectList.size()<=0) {
			dataResponse.setCode(ResponseStatusEnum.NOT_DATA.getCode());
			dataResponse.setMsg(ResponseStatusEnum.NOT_DATA.getName());
			return dataResponse;
		}
		DataCollect dataCollect = dataCollectList.get(0);
		//当录制状态为完成时，则将录制文件转为md5串
		if(!"3".equals(req.getDataState())) {
			dataResponse.setCode(ResponseStatusEnum.RECODE_STATE_ERROR.getCode());
			dataResponse.setMsg(ResponseStatusEnum.RECODE_STATE_ERROR.getName());
			return dataResponse;
		}
		DataCollect data = new DataCollect();
		data.setId(dataCollect.getId());
		//data.setRecordState(req.getRecordState());
		data.setDataState(req.getDataState());//录制状态：1-开始、2-离开、3-完成
		if(req.getRecordFinishTime()!=null&&req.getRecordFinishTime().trim().length()>0) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			data.setRecordFinishTime(sdf.parse(req.getRecordFinishTime()));
		}
		List<String> strList = null;
		//解析文件
		if(dataCollect.getUploadUrl()!=null&&dataCollect.getUploadUrl().trim().length()>0) {
			strList = readData(dataCollect.getUploadUrl());
		}
		StringBuffer sb = new StringBuffer();
		if(strList!=null) {
			for(String str:strList) {
				sb.append(str);
			}
//			String md5Str = MD5Util.toMD5(sb.toString());
			String md5Str = DigestUtils.sha256Hex(sb.toString().getBytes());
			data.setFileMd5Str(md5Str);
		}
		int count = dataCollectMapper.updateDataById(data);
		if(count==0) {
			dataResponse.setCode(ResponseStatusEnum.UPDATE_FAIL_CODE.getCode());
			dataResponse.setMsg(ResponseStatusEnum.UPDATE_FAIL_CODE.getName());
		}
		log.info(JSONObject.toJSON(dataResponse).toString());
		return dataResponse;
	}
	@Override
	public DataResponse queryApplyRecord(UpdateCollectReq req) {
		// TODO Auto-generated method stub
		DataResponse msg = new DataResponse();
		String id  = req.getId();
		List<DataCollect> dataCollectList = null;
		try {
			dataCollectList = dataCollectMapper.queryApplyRecord(id);
			msg.setMsg(ResponseStatusEnum.SUCCESS_CODE.getName());
			msg.setCode(ResponseStatusEnum.SUCCESS_CODE.getCode());
		} catch (Exception e) {
			// TODO: handle exception
			log.error(e);
			msg.setCode(ResponseStatusEnum.EXCEPTION.getCode());
			msg.setMsg(ResponseStatusEnum.EXCEPTION.getName() + "；" + e.getMessage());
			
		}
		msg.setData(dataCollectList);
		return msg;
	}
	
	/**
	 * 下载文件
	 */
	public void downloadFile(SaveCollectRequest req) throws Exception {
//		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String key = "v2"+sdf.format(new Date())+req.getSystemCode();
		String flag = redisUtil.getStr(key);
		//若当前为不下载状态则不下载该数据 0-不下载、1-下载
		/*if("0".equals(flag)) {
			return;
		}*/
		//检查当前版本是否为最新版本
		DataResponse dataResponse = this.compareHtml(req);
		if(ResponseStatusEnum.UPDATE_HTML.getCode().equals(dataResponse.getCode())) {
			redisUtil.setStr(key, "1");
			//设置时间为一天
			redisUtil.setExpire(key, 24*60*60*1000);
		}
		
		// 查询系统版本表，若查询为空则新增
		String newVersionId = UUID.randomUUID().toString();// 最新versionUUID
		//保存并下载html
		this.downloadHTML(req,newVersionId);
		//保存并下载js、css等相关静态文件
		this.downloadJS(req, newVersionId);
		
		redisUtil.setStr(key, "0");
	}
	
	
	
	/**
	 * 下载html
	 * @param req
	 * @throws Exception 
	 */
	public void downloadHTML(SaveCollectRequest req,String newVersionId){
		
		List<HtmlData>list = req.getHtmlArray();
		if(list==null||list.size()<=0) {
			return;
		}
		
		SysmaintainVersion version = null;
		SysMaintain sysMaintain = null;
		//若系统编码为空，则不下载
		if(req.getSystemCode()==null||req.getSystemCode().trim().length()<=0) {
			return ;
		}
		// 若有系统编码字段 则查询系统表，若查询不到数据，则不下载
		sysMaintain = sysMaintainMapper.queryBySystemNo(req.getSystemCode());
		//若sysMaintain为空，则说明没有配置下载页面,无需下载
		if (sysMaintain == null || null == sysMaintain.getId() || sysMaintain.getId().trim().length() <= 0) {
			/*sysMaintain = new SysMaintain();
			sysMaintain.setId(UUID.randomUUID().toString());
			sysMaintain.setSystemNo(req.getSystemCode());
			sysMaintainMapper.saveSysMaintain(sysMaintain);*/
			return;
		}
		/*String systemFlagStr = "";
		String systemurl = "";
		if(sysMaintain!=null&&sysMaintain.getSystemFlagStr()!=null&&sysMaintain.getSystemUrl()!=null) {
			systemFlagStr = sysMaintain.getSystemFlagStr();
			systemurl = sysMaintain.getSystemUrl();
		}*/
//		boolean changeFlag = false;
		// 保存版本表
		String oldVersionId = "";
		String newVersionNo = ResponseStatusEnum.VERSION.getCode();//V0001初始值
		List<SysmaintainVersion> versionList = sysMaintainVersionMapper.queryBySystemNo(req.getSystemCode());

		if (null == versionList || versionList.size() <= 0) {
			//系统编码中还没有版本记录
			version = new SysmaintainVersion();
		} else {
			version = versionList.get(0);//最新版本记录
			oldVersionId = version.getSysversionId();
			if(!sdflag) {
				newVersionNo = getVersionNo(version.getVersionNo());//在数据的最新版本基础上+1；
			}
		}
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String todayStr = sdf.format(new Date());//当天日期20201126
		String versionkey = "v2"+todayStr + req.getSystemCode() + "Version";//redis中存储着项目最新的版本信息
		//若redis有版本号，则以redis版本号为主，若无，则增加
		String newVersion = redisUtil.getStr(versionkey);
		if(newVersion!=null&&newVersion.trim().length()>0) {
			newVersionNo = newVersion;//此处newVersionNo代表redis保存的版本信息
		}else {
			redisUtil.setStr(versionkey, newVersionNo);
			redisUtil.setExpire(versionkey, 24*60*60*1000);//默认为一天
		}
		//若最新版本与当前版本相同 则用同一versionid
		if(newVersion!=null&&newVersion.trim().length()>0&&version!=null&&version.getVersionNo()!=null&&version.getVersionNo().trim().length()>0&&
				version.getSysversionId()!=null&&version.getSysversionId().trim().length()>0&&newVersion.equals(version.getVersionNo())) {
			//这个判断是redis中存储的版本号与数据库中最新的版本号一致
			//newVersionId是入参，redis取的系统版本的id
			newVersionId = version.getSysversionId();//这个赋值，此处newVersionId代表数据库中版本系统的id
		}
		//若有老版本且未生成新版本号，则copy老版本数据至新版本
		//newVersionNo数据库老版本+1
		if(!ResponseStatusEnum.VERSION.getCode().equals(newVersionNo)&&(newVersion==null||newVersion.trim().length()<=0)) {
			this.copyOld2New(version,newVersionNo,newVersionId);//redis如果没有存储，newVersionId为随机生成的uuid
		}
		// 处理山东城商行版本begin
		if (sdflag && req.getVersion() != null && req.getVersion().trim().length() > 0) {
			newVersionNo = req.getVersion();//山东的newVersionNo是在req中前端传
			log.info("联盟的版本号1："+newVersionNo);
		}
		
		
		// 处理ABC版本end
		//创建新版本
		version.setSysmaintainId(sysMaintain.getId());// sysmaintainId
		version.setVersionNo(newVersionNo);// 版本号
		SysmaintainVersion vs = new SysmaintainVersion();
		vs.setSysmaintainId(sysMaintain.getId());// sysmaintainId
		vs.setVersionNo(newVersionNo);// 版本号
		
		List<SysmaintainVersion> versionlist = sysMaintainVersionMapper.querySysMaintainVersion(vs);
		version.setVersionUpdateTime(new Date());// 版本维护时间
		version.setSysversionId(newVersionId);// 版本id
		if(versionlist==null||versionlist.size()<=0) {
			//===只有一种情况走这个判断，redis中的版本号为null
			sysMaintainVersionMapper.saveSysMaintainVersion(version);
		}

		//req.setVersion(newVersionNo);
		//保存html文件
		for(HtmlData data:list) {
			if(data==null||null==data.getUrl()||data.getUrl().trim().length()<=0||
					data.getHtmlData()==null||data.getHtmlData().trim().length()<=0) {
				continue;
			}
			
			String htmlurl = data.getUrl();
			//处理ABC数据 begin
			/*if("ABC".equals(req.getSystemCode())&&htmlurl.indexOf("LaiShangBank.app/")>-1) {
				int num = htmlurl.indexOf("LaiShangBank.app/");
				htmlurl = htmlurl.substring(num);
				htmlurl = htmlurl.substring(htmlurl.indexOf("/")+1);
				htmlurl = staticUrl + htmlurl;
			}*/
			/*if("ABC".equals(req.getSystemCode())&&systemFlagStr.trim().length()>0
					&&systemurl.trim().length()>0&&htmlurl.indexOf(systemFlagStr)>-1) {
				int num = htmlurl.indexOf(systemFlagStr);
				htmlurl = (systemurl +"/"+ htmlurl.substring(num)).replaceAll("//", "/");
			}*/
			//处理ABC数据 end
			if(htmlurl.indexOf("?")>-1) {
				htmlurl.substring(0, htmlurl.lastIndexOf("?"));
			}
			String htmlName = htmlurl.substring(htmlurl.lastIndexOf("/")+1);
			if(htmlName.indexOf("?")>-1) {
				htmlName = htmlName.substring(0,htmlName.indexOf("?"));
			}
			if(htmlName.indexOf(".html")<0) {
				htmlName+=".html";
			}
			if(!htmlName.endsWith(".html")) {
				htmlName+=".html";
			}
			/*SysMaintainVersionUrl url = sysMaintainVersionUrlMapper.queryByHtmlname(oldVersionId,htmlName);
			SysMaintainVersionUrl newversionUrl = compareVersion(url,htmlurl);*/
			/*//版本未改变
			if(newversionUrl==null) {
				continue;
			}*/
			//版本改变
//			changeFlag = true;
			String htmlPath = filePath + req.getSystemCode()+"/"+ newVersionNo ;//保存静态资源的文件夹/u01/systembak/系统编码/版本号
			
			if(htmlurl.indexOf(".html")>0) {
				//处理https://www.bjnfbk.com/NrrWeb_dev/index.html#/ProductList
				String path = htmlurl.substring(0,htmlurl.indexOf(".html"));
				int num = htmlurl.indexOf("//")+2;
				num = htmlurl.indexOf("/",num);
//				num = htmlurl.indexOf("/",num+1);
				if(path.lastIndexOf("/")!=num) {//  //后面不是只有一个/
					htmlPath =htmlPath+"/"+ path.substring(num+1, path.lastIndexOf("/"));//path.substring(num+1, path.lastIndexOf("/")为// 后面第一个与最后1个之间
				}
			}
			File file = new File(htmlPath);
			
	        //如果文件夹不存在则新建
	        if(!file.exists()) {
	        	file.mkdirs();
	        }
	        SysMaintainVersionUrl newversionUrl = new SysMaintainVersionUrl();
			newversionUrl.setSysversionId(newVersionId);
			newversionUrl.setHtmlUrl(htmlurl);
			List<SysMaintainVersionUrl> urlList = sysMaintainVersionUrlMapper.queryversionurl(newversionUrl);//某一个版本系统的某一个html文件在数据库中记录
			newversionUrl.setFileName(htmlName);
			newversionUrl.setFileUrl(htmlPath);
			newversionUrl.setUpdateTime(new Date());
			newversionUrl.setHtmlUrl(htmlurl);
			newversionUrl.setHtmlMd5Str(data.getMd5HtmlStr());
			//修改html引入绝对路径链接
			/*String newHtmlData = "";
			List<String> reList = req.getLinkArray();
			for(String strurl:reList) {
				//若html有绝对路径链接 则替换为本地连接
				if(data.getHtmlData().indexOf(strurl)>-1) {
					String path = "";
					// 获取文件名称
					String filename = strurl.substring(strurl.lastIndexOf("/") + 1);
					// 获取文件路径
					log.info("url:"+strurl);
					int num = strurl.indexOf("//") + 2;
					num = strurl.indexOf("/", num);
//					num = url.indexOf("/", num + 1);
					if(strurl.lastIndexOf("/")==num) {
						path = htmlPath;
					}else {
						path =  htmlPath + strurl.substring(num + 1, strurl.lastIndexOf("/"));
					}
					String newFile = path +"/"+ filename;
					//本地服务器访问路径 
					String newjsurl = newFile.replace("/u01", "https://www.bjnfbk.com");
					newHtmlData = data.getHtmlData().replace(strurl, newjsurl);
					data.setHtmlData(newHtmlData);
				}
			}*/
			//修改html引入绝对路径链接
			try {
				//htmlPath为本地存储的路径
				//=====测试黄河========================20210113==============
				String regEx_script = "<script[^>]*?>[\\s\\S]*?<\\/script>";
				Pattern p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
				Matcher m_script = p_script.matcher(data.getHtmlData());
				String htmlStr = m_script.replaceAll("");
				createFile(htmlPath+"/"+htmlName, htmlStr);
				//=====测试黄河========================20210113==============
//				createFile(htmlPath+"/"+htmlName, data.getHtmlData());//下载html页面
				if(urlList!=null&&urlList.size()>0) {
					sysMaintainVersionUrlMapper.updateVersionUrl(newversionUrl);
				}else {
					sysMaintainVersionUrlMapper.saveVersionUrl(newversionUrl);
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				log.error(e);
			}
		}
		//若版本改变，则增加版本
//		if(changeFlag) {
			
//		}
	}
	
	/**
	 * 拷贝上个版本数据到本次版本
	 * @param version
	 * @param newVersionNo
	 * @param newVersionId 
	 */
	public void copyOld2New(SysmaintainVersion version, String newVersionNo, String newVersionId) {

		if(version==null||version.getSysversionId()==null||version.getSysversionId().trim().length()<=0
				||version.getVersionNo()==null||version.getVersionNo().trim().length()<=0) {
			return;
		}
		SysMaintainVersionUrl versionurl = new SysMaintainVersionUrl();
		versionurl.setSysversionId(version.getSysversionId());
		List<SysMaintainVersionUrl> newurlList = new ArrayList<SysMaintainVersionUrl>();
		List<SysMaintainVersionUrl> versionurlList = sysMaintainVersionUrlMapper.queryversionurl(versionurl);//返回现有的最新版本的静态资源url记录
		for(SysMaintainVersionUrl oldversion:versionurlList) {
			SysMaintainVersionUrl newversion = new SysMaintainVersionUrl();
			newversion.setSysversionId(newVersionId);
			newversion.setHtmlUrl(oldversion.getHtmlUrl());
			/*List<SysMaintainVersionUrl> url = sysMaintainVersionUrlMapper.queryversionurl(newversion);
			//若根据版本
			if(url!=null&&url.size()>0) {
				continue;
			}*/
			//替换老版本路径为新版本路径
			String oldVersionUrl = oldversion.getFileUrl();
			String newVersionUrl = oldVersionUrl.replace(version.getVersionNo(), newVersionNo);
			newversion.setFileUrl(newVersionUrl);
			newversion.setFileName(oldversion.getFileName());
			newversion.setHtmlMd5Str(oldversion.getHtmlMd5Str());
			newversion.seteTag(oldversion.geteTag());
			newversion.setLastModified(oldversion.getLastModified());
			newversion.setUpdateTime(new Date());
			newurlList.add(newversion);
			//复制旧版本文件到新版本
			this.copyFile(oldVersionUrl, newVersionUrl, oldversion.getFileName());
		}
		sysMaintainVersionUrlMapper.saveVersionUrlList(newurlList);
	}

	/**
	 * 将文件从旧路径复制到新路径下
	 * @param oldurl 旧路径
	 * @param newurl 新路径
	 * @param fileName 文件名称
	 */
	public void copyFile(String oldurl,String newurl, String fileName) {
		
		
		File oldfile = new File(oldurl+"/"+fileName);
		File newfile = new File(newurl+"/"+fileName);
		//若文件不存在则不复制
		if(!oldfile.exists()) {
			return;
		}
		File newfileurl = new File(newurl);
		//如果文件夹不存在则新建
        if(!newfileurl.exists()) {
        	newfileurl.mkdirs();
        }
		InputStream is = null;
		OutputStream os = null;
		try {
			is = new DataInputStream(new BufferedInputStream(new FileInputStream(oldfile)));
			os = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(newfile)));
			int length = 0;
			byte[] b = new byte[1024];
			while((length=is.read(b))!=-1) {
				os.write(b, 0, length);
			}
		} catch (Exception e) {
			log.error(e);
		}finally {
			try {
				is.close();
				os.close();
			} catch (IOException e) {
				log.error(e);
			}
		}
	}

	/**
	 * 将一个目录下文件移到另一个目录下
	 * @param oldPath
	 * @param newPath
	 */
	public void copyFile(String oldPath, String newPath) {
		try {
			int bytesum = 0;
			int byteread = 0;
			File oldfile = new File(oldPath);
			if (oldfile.exists()) { //文件存在时
				InputStream inStream = new FileInputStream(oldPath); //读入原文件
				FileOutputStream fs = new FileOutputStream(newPath);
				byte[] buffer = new byte[1444];
				int length;
				while ( (byteread = inStream.read(buffer)) != -1) {
					bytesum += byteread; //字节数 文件大小
					System.out.println(bytesum);
					fs.write(buffer, 0, byteread);
				}
				inStream.close();
			}
		}
		catch (Exception e) {
			log.info("备份更新前协议文件失败");
		}

	}
	/**
	 * 保存并下载js
	 * @param req
	 */
	public void downloadJS(SaveCollectRequest req,String newVersionId) {
		List<String> reList = req.getLinkArray();//js\css等相关路径
		
		//------------------------
		// 保存版本表
		String oldVersionId = "";
		String systemFlagStr = "";
		String systemurl = "";
		String newVersionNo = ResponseStatusEnum.VERSION.getCode();//V0001
		SysmaintainVersion version = null;
		SysMaintain sysMaintain = sysMaintainMapper.queryBySystemNo(req.getSystemCode());
		if(sysMaintain!=null&&sysMaintain.getSystemFlagStr()!=null&&sysMaintain.getSystemUrl()!=null) {
			systemFlagStr = sysMaintain.getSystemFlagStr();
			systemurl = sysMaintain.getSystemUrl();
		}
//		List<SysmaintainVersion> versionList = sysMaintainVersionMapper.queryBySystemNo(req.getSystemCode());
		List<SysmaintainVersion> versionList = new ArrayList<>();
		SysmaintainVersion sysmaintainVersion = sysMaintainVersionMapper.queryBySystemNoAndVno(req.getSystemCode(), req.getVersion());
		if(sysmaintainVersion!=null){
			versionList.add(sysmaintainVersion);
		}
		if (null == versionList || versionList.size() <= 0) {
			version = new SysmaintainVersion();
		} else {
			version = versionList.get(0);//获取某系统最新的版本记录对象
			oldVersionId = version.getSysversionId();
			if(!sdflag) {
				newVersionNo = getVersionNo(version.getVersionNo());//不是山东的话，在数据库把最新版本上+1
			}
			
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String todayStr = sdf.format(new Date());
		String versionkey = "v2"+todayStr + req.getSystemCode() + "Version";
		// 若redis有版本号，则以redis版本号为主，若无，则增加
		String newVersion = redisUtil.getStr(versionkey);
		if (newVersion != null && newVersion.trim().length() > 0) {
			newVersionNo = newVersion;
		} else {
			redisUtil.setStr(versionkey, newVersionNo);
			redisUtil.setExpire(versionkey, 24 * 60 * 60 * 1000);// 默认为一天
		}
		// 若有老版本且未生成新版本号，则copy老版本数据至新版本
		if ((!ResponseStatusEnum.VERSION.getCode().equals(newVersionNo) && (newVersion == null || newVersion.trim().length() <= 0))&&!sdflag) {
			//redis中没有版本号信息
			this.copyOld2New(version, newVersionNo, newVersionId);//数据库url记录会变，静态资源也会复制到新版本================================20210105
		}
		//-------------------------
		// 处理山东城商行版本begin
		if (sdflag && req.getVersion() != null && req.getVersion().trim().length() > 0) {
			newVersionNo = req.getVersion();
			log.info("联盟的版本号"+newVersionNo);
		}
		// 处理ABC版本end
		String filederpath = filePath + req.getSystemCode()+"/"+ newVersionNo ;//静态资源保存路径/u01/systembak/NrrWeb/系统编号/版本号
		//获取所有需要下载的文件路径 
		log.info("获取路径数量:" + reList.size());
				//若最新版本与当前版本相同 则用同一versionid,一天只能更新一个静态资源的版本
		if (newVersion != null && newVersion.trim().length() > 0 && version != null && version.getVersionNo() != null
				&& version.getVersionNo().trim().length() > 0 && version.getSysversionId() != null
				&& version.getSysversionId().trim().length() > 0 && newVersion.equals(version.getVersionNo())) {
			//山东的newVersion为v001
			newVersionId = version.getSysversionId();
		}
		//===============================================================================++++++++++++++++++++++++++++++++++++++++
		//创建新版本
		version.setSysmaintainId(sysMaintain.getId());// sysmaintainId
		version.setVersionNo(newVersionNo);// 版本号
		SysmaintainVersion vs = new SysmaintainVersion();
		vs.setSysmaintainId(sysMaintain.getId());// sysmaintainId
		vs.setVersionNo(newVersionNo);// 版本号
		List<SysmaintainVersion> versionlist = sysMaintainVersionMapper.querySysMaintainVersion(vs);
		if (versionlist!=null&&versionlist.size()>0) {
			log.info("版本信息表里面有数据，newVersionId以数据库里面版本为主");
			newVersionId=versionlist.get(0).getSysversionId();
		}
		version.setVersionUpdateTime(new Date());// 版本维护时间
		version.setSysversionId(newVersionId);// 版本id
		if (versionlist == null || versionlist.size() <= 0) {
			//版本信息（系统编码、版本号没有才添加、有则不作处理）
			sysMaintainVersionMapper.saveSysMaintainVersion(version);
		}
		//======+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
		for (int i = 0; i < reList.size(); i++) {
			String path = "";
			String url = reList.get(i);
			log.info("url连接为："+url);


			if(!isURL(url)) {
				log.info(url+"---不是正确的http协议地址，跳出循环---");
				continue;
			}

			//处理长字符串；处理非截图的静态url
			if (!url.contains("/api/commom/image/querypicture") && url.indexOf("?")>-1 ) {
				url = url.substring(0, url.indexOf("?"));
			}
			// 获取文件名称
			String filename = url.substring(url.lastIndexOf("/") + 1);
			if(!url.contains("/api/commom/image/querypicture") && filename.indexOf("?")>-1) {
				filename = filename.substring(0,filename.indexOf("?"));
			}
			if (url.contains("/api/commom/image/querypicture")) {
				//地址需要将？和 = 替换成/
				filename=filename.replaceAll("[?,=]", "_");
			}
			// 获取文件路径
			log.info("处理后的url:"+url);
			int num = url.indexOf("//") + 2;
			num = url.indexOf("/", num);// http://后第一个/的索引值
//			num = url.indexOf("/", num + 1);
			if(url.lastIndexOf("/")==num) {
				//http://后只有1个/
				path = filederpath;
			}else {
				path = filederpath +"/"+ url.substring(num + 1, url.lastIndexOf("/"));//url.substring(num + 1, url.lastIndexOf("/")第一个到最后一个之间的
			}
			File file = new File(path);

			// 如果文件夹不存在则新建
			if (!file.exists()) {
				file.mkdirs();
			}
			//===============================对于山东条款协议的特殊处理======================================2021-0107
//			SysMaintainVersionUrl versionurl = this.compareVersion(null, url);//this.compareVersion返回的对象中保存着url静态资源的eTag与lastModified；=======
			SysMaintainVersionUrl versionurl =new SysMaintainVersionUrl();
			String sdxyurl=url;
			if(sdxyurl.contains("/image/instructions/")&&sdflag){
				sdxyurl = ebankimage + sdxyurl.substring(sdxyurl.indexOf("/image/instructions/"), sdxyurl.length());//生产上逻辑
				//sdxyurl="http://localhost:8080/slxt-web/assets/image/instructions/66824cceec91fd16c6b32aaf83311225.jpeg";//测试逻辑
				versionurl = this.compareVersion(null, sdxyurl);
			}
//			url=sdxyurl;
			/*if (sdxyurl.contains("static/public")&&sdflag){
				log.info("运维项目需要下载的静态资源原连接："+sdxyurl);
				sdxyurl = CollectDataServiceImpl.staticresource + sdxyurl.substring(sdxyurl.indexOf("static/public")+"static".length());
				log.info("运维项目需要下载的静态资源内网链接："+sdxyurl);
			}*/
			if (sdxyurl.indexOf("?")>-1) {
				sdxyurl=sdxyurl.substring(0,sdxyurl.indexOf("?"));
			}
			//===============================对于山东条款协议的特殊处理======================================2021-01-07
			versionurl.setHtmlUrl(sdxyurl);
			versionurl.setSysversionId(newVersionId);
			versionurl.setFileName(filename);
			versionurl.setFileUrl(path+"/"+versionurl.getLastModified().replaceAll("\\s*", ""));
			versionurl.setUpdateTime(new Date());

			//下载数据
			DataResponse dataResponse = this.downLoadJS(url, path,filename);//下载js===

			//若成功下载则修改数据库
			if(ResponseStatusEnum.SUCCESS_CODE.getCode().equals(dataResponse.getCode())) {
				SysMaintainVersionUrl queryurl = new SysMaintainVersionUrl();
				queryurl.setHtmlUrl(url);
				queryurl.setSysversionId(newVersionId);
				List<SysMaintainVersionUrl> urlList = sysMaintainVersionUrlMapper.queryversionurl(queryurl);
				if(urlList!=null&&urlList.size()>0) {
					log.info(JSONObject.toJSON(versionurl).toString());
					sysMaintainVersionUrlMapper.updateVersionUrl(versionurl);
				}else {
					sysMaintainVersionUrlMapper.saveVersionUrl(versionurl);
				}
			}
		}
//		downfile.downLoadFile(req.getLinkArray(), filederpath, req.getUuid(), null, req.getStartTime());
	}
	 /**
     * 判断一个字符串是否为url
     * @param str String 字符串
     * @return boolean 是否为url
     * @author peng1 chen
     * **/
    public static boolean isURL(String str){
        //转换为小写
        str = str.toLowerCase();
        String regex = "^((https|http|ftp|rtsp|mms)?://)"  //https、http、ftp、rtsp、mms
                + "?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?" //ftp的user@  
               + "(([0-9]{1,3}\\.){3}[0-9]{1,3}" // IP形式的URL- 例如：199.194.52.184  
                 + "|" // 允许IP和DOMAIN（域名）
                 + "([0-9a-z_!~*'()-]+\\.)*" // 域名- www.  
                 + "([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\\." // 二级域名  
                + "[a-z]{2,6})" // first level domain- .com or .museum  
                + "(:[0-9]{1,5})?" // 端口号最大为65535,5位数
                + "((/?)|" // a slash isn't required if there is no file name  
                + "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$";  
        return  str.matches(regex);
    }
	/**
	 * 下载js
	 * @param jsurl js链接
	 * @param localurl 下载到本地路径
	 * @param filename 文件名称
	 * @throws Exception 
	 */
	public DataResponse downLoadJS(String jsurl,String localurl, String filename) {
		
		DataResponse response = new DataResponse();
		response.setCode(ResponseStatusEnum.SUCCESS_CODE.getCode());
		response.setMsg(ResponseStatusEnum.SUCCESS_CODE.getName());
		URL fileurl;
		FileOutputStream fos = null;
		InputStream in = null;
		try {
			log.info("url连接:" + jsurl);
			if (jsurl.contains("/image/instructions/")&&sdflag) {
            	// 只有山东的系统，地址需要将外网地址 替换成内网地址
				// 例如：https://866.ebank.com.cn/image/instructions/*** 外网地址
				// 例如：http://ebankimage:8095/image/instructions/***  内网地址
				log.info("/image/instructions/的url要进行协议转换，外网地址改成内网地址。");
				//jsurl=jsurl.replaceAll("https", "http");
				
				jsurl = ebankimage + jsurl.substring(jsurl.indexOf("/image/instructions/"), jsurl.length());//外网地址换成内网地址http://39.0.131.3:8095
				//jsurl = "http://localhost:8080/slxt-web/assets/image/instructions/66824cceec91fd16c6b32aaf83311225.jpeg";//外网地址换成内网地址http://39.0.131.3:8095
				log.info("替换后的url连接:" + jsurl);
			}
			if (jsurl.contains("static/public")&&sdflag){
				log.info("js真是下载,运维项目需要下载的静态资源原连接："+jsurl);
				jsurl = CollectDataServiceImpl.staticresource + jsurl.substring(jsurl.indexOf("static/public")+"static".length());
				log.info("js真是下载,运维项目需要下载的静态资源内网链接："+jsurl);
			}
			//=======================================================================判断是否超时
			//=======================================================================
			fileurl = new URL(jsurl);
			// 获取连接
			URLConnection conn = fileurl.openConnection();
			// 设置三秒连接超时
			conn.setConnectTimeout(3000);
			in = conn.getInputStream();
			// 创建文件路径
			//localurl==================================================山东协议特殊处理
			if(jsurl.contains("/image/instructions/")&&sdflag){
				SysMaintainVersionUrl sysMaintainVersionUrl = this.compareVersion(null, jsurl);
				localurl=localurl+"/"+sysMaintainVersionUrl.getLastModified().replaceAll("\\s*", "");
				log.info("---------条款协议保存在"+localurl+"目录下--------");
			}
			//localurl==================================================山东协议特殊处理
			File filePath = new File(localurl);
			if (!filePath.exists()) {
				filePath.mkdirs();
			}
			String newFileurl = localurl +"/"+ filename;
			log.info("文件保存地址:" + newFileurl);
			fos = new FileOutputStream(new File(newFileurl));
			byte[] by = new byte[1024*10];
			int len = 0;
			while ((len = in.read(by))>0){
				fos.write(by,0,len);
			}
		} catch (Exception e) {
			log.error(e);
			response.setCode(ResponseStatusEnum.FAIL_CODE.getCode());
			response.setMsg(ResponseStatusEnum.FAIL_CODE.getName());
			return response;
		}finally {
			try {
				if(fos!=null) {
					fos.close();
				}
				if(in!=null) {
					in.close();
				}
			} catch (IOException e) {
				log.error(e);
			}
		}
		return response;
	}
	
	/**
	 * 检查是否下载最新版本静态文件
	 * @param req
	 */
	public DataResponse checkFile(SaveCollectRequest req) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		DataResponse response = new DataResponse();
		response.setCode(ResponseStatusEnum.UPDATE_HTML.getCode());
		response.setMsg(ResponseStatusEnum.UPDATE_HTML.getName());
		String key = "v2"+sdf.format(new Date())+req.getSystemCode();//当前年月日+系统编码
		String flag = redisUtil.getStr(key);
		//flag 0-不下载 ，1-下载
		if("0".equals(flag)) {
			response.setCode(ResponseStatusEnum.NOT_UPDATE_HTML.getCode());
			response.setMsg(ResponseStatusEnum.NOT_UPDATE_HTML.getName());
			return response;
		}
		response.setCode(ResponseStatusEnum.UPDATE_HTML.getCode());
		response.setMsg(ResponseStatusEnum.UPDATE_HTML.getName());
		return response;
	}
	
	public DataResponse compareHtml(SaveCollectRequest req){
		
		DataResponse response = new DataResponse();
		response.setCode(ResponseStatusEnum.UPDATE_HTML.getCode());
		response.setMsg(ResponseStatusEnum.UPDATE_HTML.getName());
		List resList = new ArrayList<CompareHtmlRes>(); 
		SysmaintainVersion version = null;
		SysMaintain sysMaintain = null;
		// 若有系统编码字段 则查询系统表，若查询不到数据，则返回空
		sysMaintain = sysMaintainMapper.queryBySystemNo(req.getSystemCode());
		if (sysMaintain == null || null == sysMaintain.getId() || sysMaintain.getId().trim().length() <= 0) {
			return response;
		}
		List<SysmaintainVersion> versionList = sysMaintainVersionMapper.queryBySystemNo(req.getSystemCode());
		if (null == versionList || versionList.size() <= 0) {
			return response;
		}
		version = versionList.get(0);
		String oldVersionId = version.getSysversionId();// 最新versionUUID
		if(oldVersionId==null||oldVersionId.trim().length()<=0) {
			return response;
		}
		//轮询所有html文件链接,只要有一个得ETag和Last-Modified改变则返回更新状态
		for(HtmlData data:req.getHtmlArray()) {
			
			if(data==null||null==data.getUrl()||data.getUrl().trim().length()<=0){
				continue;
			}
			CompareHtmlRes res = new CompareHtmlRes();
			res.setUrl(data.getUrl());
			String htmlurl = data.getUrl();
			String htmlName = htmlurl.substring(htmlurl.lastIndexOf("/")+1);
			if(htmlName.indexOf("?")>-1) {
				htmlName = htmlName.substring(0,htmlName.indexOf("?"));
			}
			if(htmlurl.indexOf(".html")<0) {
				htmlName+=".html";
			}
			SysMaintainVersionUrl url = sysMaintainVersionUrlMapper.queryByHtmlname(oldVersionId,htmlName);
			SysMaintainVersionUrl newversionUrl = compareVersion(url, htmlurl);//====
			if(url!=null&&newversionUrl!=null&&newversionUrl.geteTag().equals(url.geteTag())&&newversionUrl.getLastModified().equals(url.getLastModified())) {
				continue;
			}
			//更新静态文件
			response.setCode(ResponseStatusEnum.UPDATE_HTML.getCode());
			response.setMsg(ResponseStatusEnum.UPDATE_HTML.getName());
			return response;
		}
		//轮询所有js\css等静态文件链接,只要有一个得ETag和Last-Modified改变则返回更新状态
		for(String url : req.getLinkArray()) {
			if(url==null||url.trim().length()<=0){
				continue;
			}
			//静态文件名
			String htmlName = url.substring(url.lastIndexOf("/")+1);
			SysMaintainVersionUrl versionUrl = sysMaintainVersionUrlMapper.queryByHtmlname(oldVersionId,htmlName);
			SysMaintainVersionUrl newversionUrl = compareVersion(versionUrl, url);
			if(versionUrl!=null&&newversionUrl!=null&&newversionUrl.geteTag().equals(versionUrl.geteTag())&&newversionUrl.getLastModified().equals(versionUrl.getLastModified())) {
				continue;
			}
			//更新静态文件
			response.setCode(ResponseStatusEnum.UPDATE_HTML.getCode());
			response.setMsg(ResponseStatusEnum.UPDATE_HTML.getName());
			return response;
		}
		response.setCode(ResponseStatusEnum.NOT_UPDATE_HTML.getCode());
		response.setMsg(ResponseStatusEnum.NOT_UPDATE_HTML.getName());
		return response;
		
	}
	
	/**
	 * 判断是否对比html
	 */
	public DataResponse isNotCompareHtml(String sysCode){
		
		DataResponse dataResponse = new DataResponse();
		dataResponse.setCode(ResponseStatusEnum.COMPARE.getCode());
		dataResponse.setMsg(ResponseStatusEnum.COMPARE.getName());
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String todayStr = sdf.format(new Date());
		String key = "v2"+todayStr + sysCode + "Html";
		String keyFlag = key + "flag";
		String flag = redisUtil.getStr(keyFlag);//比对标识：0-不对比 1-对比
		//不对比
		if("0".equals(flag)) {
			dataResponse.setCode(ResponseStatusEnum.NOT_COMPARE.getCode());
			dataResponse.setMsg(ResponseStatusEnum.NOT_COMPARE.getName());
			return dataResponse;
		}
		if("1".equals(flag)) {
			return dataResponse;
		}
		List<SysMaintainHtml> htmlList = sysMaintainHtmlMapper.queryBySysCode(sysCode);
		//若接入系统未配置该数据则提示其配置相关页面连接
		if(htmlList==null||htmlList.size()<=0) {
			dataResponse.setCode(ResponseStatusEnum.CONFIG_HTML.getCode());
			dataResponse.setMsg(ResponseStatusEnum.CONFIG_HTML.getName());
			return dataResponse;
		}
		for(SysMaintainHtml html:htmlList) {
			if(html.getFileUrl()!=null&&html.getFileUrl().trim().length()>0) {
				//处理ABC数据 begin
				String url = html.getFileUrl();
				if(sdflag) {
					redisUtil.rightPushList(key, url);
					continue;
				}
				//处理ABC数据 end
				redisUtil.rightPushList(key, html.getFileUrl());
			}
		}
		redisUtil.setStr(keyFlag, "1");
		redisUtil.setExpire(keyFlag, 24*60*60*1000);//设置过期时间为一天
		return dataResponse;
	}
	
	/**
	 * 比对html和js是否下载
	 * @param req
	 * @return
	 */
	public DataResponse compare(SaveCollectRequest req) {
		
		DataResponse res = this.compareHtml_new(req);//这一块是比较html=======
		if(ResponseStatusEnum.NOT_UPDATE_HTML.getCode().equals(res.getCode())) {
			downfile.compareAnddownload(req);//这是比较js
		}
		return res;
	}
	
	
	/**
	 * 对比html是否下载
	 * @param req
	 * @return
	 */
	public DataResponse compareHtml_new(SaveCollectRequest req) {
		
		DataResponse dataResponse = new DataResponse();
		if(req==null||req.getHtmlArray()==null||req.getHtmlArray().size()<=0||req.getSystemCode()==null||req.getSystemCode().trim().length()<=0) {
			dataResponse.setCode(ResponseStatusEnum.PARAM_IS_NULL.getCode());
			dataResponse.setMsg(ResponseStatusEnum.PARAM_IS_NULL.getName());
			return dataResponse;
		}
		List<HtmlData> htmlDataList = req.getHtmlArray();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String todayStr = sdf.format(new Date());
		String key = todayStr + req.getSystemCode() + "Html";//存放要比对的html路径
		String keyFlag = key + "flag";//比对标识：0-不对比 1-对比

		List<SysmaintainVersion> verList = sysMaintainVersionMapper.queryBySystemNo(req.getSystemCode());
		//若该系统没有版本，则下载html
		if(verList==null||verList.size()<=0) {
			dataResponse.setCode(ResponseStatusEnum.UPDATE_HTML.getCode());
			dataResponse.setMsg(ResponseStatusEnum.UPDATE_HTML.getName());
			return dataResponse;
		}
		//若该系统有版本，则取最新版本
		SysmaintainVersion version = verList.get(0);
		//若最新版本没有关联versionid，则下载
		if(version==null||version.getSysversionId()==null||version.getSysversionId().trim().length()<=0) {
			dataResponse.setCode(ResponseStatusEnum.UPDATE_HTML.getCode());
			dataResponse.setMsg(ResponseStatusEnum.UPDATE_HTML.getName());
			return dataResponse;
		}
		
		for(HtmlData data:htmlDataList) {
			String url = data.getUrl();
			if(url.indexOf("?")>-1) {
				url = url.substring(0,url.lastIndexOf("?"));//url去除get传参
			}
			SysMaintainVersionUrl versionurl = new SysMaintainVersionUrl();
			versionurl.setSysversionId(version.getSysversionId());
			versionurl.setHtmlUrl(url);
			List<SysMaintainVersionUrl> urlList = sysMaintainVersionUrlMapper.queryversionurl(versionurl);
			if(urlList==null||urlList.size()<=0) {
				dataResponse.setCode(ResponseStatusEnum.UPDATE_HTML.getCode());
				dataResponse.setMsg(ResponseStatusEnum.UPDATE_HTML.getName());
				return dataResponse;
			}
			SysMaintainVersionUrl versionUrl = urlList.get(0);
			//若查询结果为空或空对象则下载
			if(versionUrl==null||versionUrl.getSysversionId()==null||versionUrl.getSysversionId().length()<=0) {
				dataResponse.setCode(ResponseStatusEnum.UPDATE_HTML.getCode());
				dataResponse.setMsg(ResponseStatusEnum.UPDATE_HTML.getName());
				return dataResponse;
			}
			//若md5串不相同则下载
			if(!data.getMd5HtmlStr().equals(versionUrl.getHtmlMd5Str())) {//===========像山东那种外网访问不到的html，前端传的md5HtmlStr值是多少
				dataResponse.setCode(ResponseStatusEnum.UPDATE_HTML.getCode());
				dataResponse.setMsg(ResponseStatusEnum.UPDATE_HTML.getName());
				return dataResponse;
			}
		}
		dataResponse.setCode(ResponseStatusEnum.NOT_UPDATE_HTML.getCode());
		dataResponse.setMsg(ResponseStatusEnum.NOT_UPDATE_HTML.getName());
		return dataResponse;
	}
	
	/**
	 * 判断js是否需要下载
	 * @param req
	 * @return
	 */
	public DataResponse compareJS(SaveCollectRequest req) {
		
		DataResponse dataResponse = new DataResponse();
		if(req==null||req.getSystemCode()==null||req.getSystemCode().trim().length()<=0) {
			dataResponse.setCode(ResponseStatusEnum.PARAM_IS_NULL.getCode());
			dataResponse.setMsg(ResponseStatusEnum.PARAM_IS_NULL.getName());
			return dataResponse;
		}
		List<String> linkList = req.getLinkArray();
		if(linkList==null||linkList.size()<=0) {
			dataResponse.setCode(ResponseStatusEnum.NOT_UPDATE_JS.getCode());
			dataResponse.setMsg(ResponseStatusEnum.NOT_UPDATE_JS.getName());
			return dataResponse;
		}
		String systemFlagStr = "";
		String systemurl = "";
		SysMaintain sysmaintain = sysMaintainMapper.queryBySystemNo(req.getSystemCode());
		if(sysmaintain!=null&&sysmaintain.getSystemFlagStr()!=null&&sysmaintain.getSystemUrl()!=null) {
			systemFlagStr = sysmaintain.getSystemFlagStr();
			systemurl = sysmaintain.getSystemUrl();
		}
		//山东的版本信息数据根据系统编码与版本号拿取。
		List<SysmaintainVersion> versionList = new ArrayList<>();
		SysmaintainVersion sysmaintainVersion = sysMaintainVersionMapper.queryBySystemNoAndVno(req.getSystemCode(), req.getVersion());
		if(sysmaintainVersion!=null){
			versionList.add(sysmaintainVersion);
		}
		//若该系统没有版本，则下载js
		if (versionList == null || versionList.size() <= 0) {
			dataResponse.setCode(ResponseStatusEnum.UPDATE_JS.getCode());
			dataResponse.setMsg(ResponseStatusEnum.UPDATE_JS.getName());
			return dataResponse;
		}
		// 若该系统有版本，则取最新版本
		SysmaintainVersion version = versionList.get(0);
		// 若最新版本没有关联versionid，则下载
		if (version == null || version.getSysversionId() == null || version.getSysversionId().trim().length() <= 0) {
			dataResponse.setCode(ResponseStatusEnum.UPDATE_JS.getCode());
			dataResponse.setMsg(ResponseStatusEnum.UPDATE_JS.getName());
			return dataResponse;
		}
		for(String jsUrl : linkList) {
			if(jsUrl==null||jsUrl.trim().length()<=0) {
				continue;
			}
			//==================================================山东的条款协议特殊处理=======================20210107==
			String sdurl=jsUrl;
			if (!sdurl.contains("/api/commom/image/querypicture") && sdurl.indexOf("?")>-1 ) {
				sdurl = sdurl.substring(0, sdurl.indexOf("?"));
			}
			if (sdurl.contains("/image/instructions/")&&sdflag){
				jsUrl=sdurl;
				jsUrl = ebankimage + jsUrl.substring(jsUrl.indexOf("/image/instructions/"), jsUrl.length());//生产上处理逻辑
			}
			//==================================================山东的条款协议特殊处理=======================20210107==
			//===================================================运维二期的下载静态资源
			/*if (sdurl.contains("static/public")&&sdflag){
				jsUrl=sdurl;
				log.info("运维项目需要下载的静态资源原连接："+jsUrl);
				jsUrl = CollectDataServiceImpl.staticresource + jsUrl.substring(jsUrl.indexOf("static/public")+"static".length());
				log.info("运维项目需要下载的静态资源内网链接："+jsUrl);
			}*/
			//===================================================运维二期的下载静态资源
			//处理ABC数据 end
			//验证该链接是否可以下载
			DataResponse resp = this.connectState(jsUrl);//====
			//若链接失败则不下载
			if(ResponseStatusEnum.FAIL_CODE.getCode().equals(resp.getCode())) {
				continue;
			}
			String url = jsUrl;
			if(url.indexOf("?")>-1) {
				url = url.substring(0,url.lastIndexOf("?"));//去参数后的内网链接
			}
			SysMaintainVersionUrl versionurl = new SysMaintainVersionUrl();
			versionurl.setSysversionId(version.getSysversionId());
			versionurl.setHtmlUrl(url);
			List<SysMaintainVersionUrl> urlList = sysMaintainVersionUrlMapper.queryversionurl(versionurl);
			log.info("jsUrl查询结果:"+jsUrl+"===result:"+JSONObject.toJSONString(urlList).toString());
			if(urlList==null||urlList.size()<=0) {
				dataResponse.setCode(ResponseStatusEnum.UPDATE_JS.getCode());
				dataResponse.setMsg(ResponseStatusEnum.UPDATE_JS.getName());
				return dataResponse;
			}
			SysMaintainVersionUrl versionUrl = urlList.get(0);
			//若查询结果为空或空对象则下载
			if(versionUrl==null||versionUrl.getSysversionId()==null||versionUrl.getSysversionId().length()<=0) {
				dataResponse.setCode(ResponseStatusEnum.UPDATE_JS.getCode());
				dataResponse.setMsg(ResponseStatusEnum.UPDATE_JS.getName());
				return dataResponse;
			}
			SysMaintainVersionUrl newversionUrl = compareVersion(versionUrl, jsUrl);
			//若newversionUrl不为空null,则说明该静态文件的etag\lastmodify改变了,需要下载
			if(newversionUrl!=null) {
				dataResponse.setCode(ResponseStatusEnum.UPDATE_JS.getCode());
				dataResponse.setMsg(ResponseStatusEnum.UPDATE_JS.getName());
				return dataResponse;
			}
		}
		dataResponse.setCode(ResponseStatusEnum.NOT_UPDATE_JS.getCode());
		dataResponse.setMsg(ResponseStatusEnum.NOT_UPDATE_JS.getName());
		return dataResponse;
	}
	
	
	/**
	 * 测试该静态文件链接是否能访问下载
	 * @param jsUrl
	 * @return
	 */
	public DataResponse connectState(String jsUrl) {
		DataResponse dataResponse = new DataResponse();
		dataResponse.setCode(ResponseStatusEnum.SUCCESS_CODE.getCode());
		dataResponse.setMsg(ResponseStatusEnum.SUCCESS_CODE.getName());
		InputStream in =null;
		try {
			log.info("url连接:" + jsUrl);
			URL fileurl = new URL(jsUrl);
			// 获取连接
			URLConnection conn = fileurl.openConnection();
			// 设置三秒连接超时
			conn.setConnectTimeout(3000);
			in = conn.getInputStream();
			if(in==null){
				dataResponse.setCode(ResponseStatusEnum.FAIL_CODE.getCode());
				dataResponse.setMsg(ResponseStatusEnum.FAIL_CODE.getName());
				return dataResponse;
			}
			byte[] by = new byte[1024*10];
			int len = 0;
			while ((len = in.read(by))>0){
				return dataResponse;
			}
		} catch (Exception e) {
			log.error(e);
			dataResponse.setCode(ResponseStatusEnum.FAIL_CODE.getCode());
			dataResponse.setMsg(ResponseStatusEnum.FAIL_CODE.getName());
			return dataResponse;
		}finally {
			try{
				if(in!=null){
					in.close();
				}
			}catch (Exception e){
				log.error(e);
			}
		}
		return dataResponse;
	}
	
	/**
	 * 下载静态资源
	 * @param req
	 * @return
	 */
	public DataResponse downloadStaticFile(SaveCollectRequest req) {
		DataResponse dataResponse = new DataResponse();
		if(req==null||req.getSystemCode()==null||req.getSystemCode().trim().length()<=0) {
			dataResponse.setCode(ResponseStatusEnum.PARAM_IS_NULL.getCode());
			dataResponse.setMsg(ResponseStatusEnum.PARAM_IS_NULL.getName());
			return dataResponse;
		}
		// 查询系统版本表，若查询为空则新增
		String newVersionId = UUID.randomUUID().toString();// 最新versionUUID
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String todayStr = sdf.format(new Date());
		String key = "v2"+todayStr + req.getSystemCode()+"Uid";//当天日期+系统编码+Uid
		String uuid = redisUtil.getStr(key);//从redis获取uuid
		if(uuid!=null&&uuid.trim().length()>0) {
			newVersionId = uuid;
		}else {
			//redis中存着系统最新版本记录的主键
			redisUtil.setStr(key, newVersionId);
			redisUtil.setExpire(key, 24*60*60*1000);	
		}
		//若html不为空
		if(req.getHtmlArray()!=null) {
			//保存并下载html
			this.downloadHTML(req,newVersionId);// newVersionId系统最新版本记录的主键
		}
		if(req.getLinkArray()!=null) {
			this.downloadJS(req, newVersionId);// newVersionId系统最新版本记录的主键
		}
		dataResponse.setCode(ResponseStatusEnum.SUCCESS_CODE.getCode());
		dataResponse.setMsg(ResponseStatusEnum.SUCCESS_CODE.getName());
		return dataResponse;
	}
	
	
	
	/**
	 * 获取视频回放插件信息
	 */
	public DataCollect queryPluginData(String id,String bussinessNo){
		DataCollect bo = new DataCollect();
		bo.setId(id);//数据主键id
		bo.setBusinessNo(bussinessNo);//业务识别号（保单号）
		List<DataCollect> dataCollectList = dataCollectMapper.queryData(bo);
		log.info("======queryDataFile视频回放接口数据查询结果:======"+JSONObject.toJSONString(dataCollectList).toString());
		if(null==dataCollectList||dataCollectList.size()<=0) {
			return null;
		}
		return dataCollectList.get(0);
	}
	

	
	/**
	 * 处理山东城商联盟文件
	 */
	public void unZipStatic(SaveCollectRequest req) {
		boolean unzipFlag=true;
		boolean comunzipFlag=true;

		SysmaintainVersion version = null;
		SysMaintain sysMaintain = null;
		//只有山东城商联盟的系统才能用此方法
		if(req==null||!sdflag||req.getVersion()==null
				||req.getVersion().trim().length()<=0) {
			return ;
		}
		// 若有系统编码字段 则查询系统表，若查询不到数据，则不下载
		sysMaintain = sysMaintainMapper.queryBySystemNo(req.getSystemCode());
		//若sysMaintain为空，则说明没有配置下载页面,无需下载
		if (sysMaintain == null || null == sysMaintain.getId() || sysMaintain.getId().trim().length() <= 0) {
			return;
		}
		//ABC传输版本
		String newVersionNo = req.getVersion();
		SysmaintainVersion sysmaintainVersion = sysMaintainVersionMapper.queryBySystemNoAndVno(req.getSystemCode(), newVersionNo);
		log.info("zip包中接入系统编码为"+req.getSystemCode());
		log.info("zip包中接入版本为"+newVersionNo);
		//若有版本则不下载
		String fileurl = sysMaintain.getFileUrl();//要下载文件的连接===生产上实际代码
		String filename = fileurl.substring(fileurl.lastIndexOf("/")+1);//下载文件名称
		//文件下载路径
		String downloadurl = filePath + req.getSystemCode() + "/" + req.getVersion() ;
		log.info("山东静态资源开始下载=====");
		File mudifile=new File(downloadurl);
		if (!mudifile.exists()) {
			//如果目录不存在
			mudifile.mkdirs();
		}
		String cplinux="";
		String unziplinux="";
		try {
            String zipTime =Md5Util1.getMd5(fileurl);
            log.info("获取zip包的md5值： "+zipTime);
			String commonzippathMd5 = Md5Util1.getMd5(CollectDataServiceImpl.commonzippath);
			log.info("获取公共目录包的md5值： "+commonzippathMd5);
			File jieya2=new File(downloadurl+"/"+"6.0Web");//此处的filename是zip包的名字
			boolean flag20=true;//解压的文件夹是否存在变量
			if(!jieya2.exists()){
				log.info("zip:解压文件夹不存在");
				flag20=false;
			}else{
				log.info("zip:解压文件夹已经存在");
			}
			//解压的文件夹存在且时间未发生变化不解压
			if(sysmaintainVersion==null){
				log.info("zip包中sysmaintainVersion为空");
				sysmaintainVersion=new SysmaintainVersion();
				//更据系统编码获取Sysmaintain
				SysMaintain sysMaintain12 = sysMaintainMapper.queryBySystemNo(req.getSystemCode());
				if (sysMaintain12==null) {
					log.info("zip包中更据系统编码获取不到接入系统的信息");
				}
				sysmaintainVersion.setSysmaintainId(sysMaintain12.getId());
				sysmaintainVersion.setVersionNo(req.getVersion());
				sysmaintainVersion.setVersionUpdateTime(new Date());
				sysmaintainVersion.setSysversionId(UUID.randomUUID().toString());
				sysMaintainVersionMapper.saveSysMaintainVersion(sysmaintainVersion);
				log.info("zip包中向数据库里面保存版本信息");
			}
			log.info("zip包中sysmaintainVersion值为"+sysmaintainVersion);
			//从redis中取MD5值
			if (flag20&&Objects.equals(redisUtil.getStr("commonzippathMd5"+req.getSystemCode()),commonzippathMd5)) {
				//公共目录没有改变
				comunzipFlag=false;
				log.info("公共目录不需要解压");
			}else{
				//公共目录md5存入redis
				redisUtil.setStr("commonzippathMd5"+req.getSystemCode(),commonzippathMd5);
			}
			//
			if(flag20&&zipTime.equals(sysmaintainVersion.getZiptime())){
				log.info("zip包不需要解压");
				unzipFlag=false;
			}
			//解压逻辑：解压zip包，并且更新数据库ziptime
			sysMaintainVersionMapper.updateSysMaintainVersionbyid(sysmaintainVersion.getSysversionId(),zipTime);
			//如果解压的文件夹不存在，条款协议重新下载
			List<String> stringListURL = req.getLinkArray();
/**
 * 			除条款协议外的下载static/public
 */
			boolean downflag=compareDownloadStaticLine(stringListURL,req.getSystemCode(),req.getVersion());
			if(downflag){
				//重新下载条款协议
				log.info("static/public的静态资源需要下载");
				for (int i = 0; i < stringListURL.size(); i++) {
					String path = "";
					String url = stringListURL.get(i);
					if(!isURL(url)) {
						continue;
					}

					if (!url.contains("static/public")&&sdflag){
						continue;
					}

					//处理长字符串；处理非截图的静态url
					if (!url.contains("/api/commom/image/querypicture") && url.indexOf("?")>-1 ) {
						url = url.substring(0, url.indexOf("?"));
					}
					// 获取文件名称
					String filename1 = url.substring(url.lastIndexOf("/") + 1);
					if(!url.contains("/api/commom/image/querypicture") && filename1.indexOf("?")>-1) {
						filename1 = filename1.substring(0,filename1.indexOf("?"));
					}
					if (url.contains("/api/commom/image/querypicture")) {
						//地址需要将？和 = 替换成/
						filename1=filename1.replaceAll("[?,=]", "_");
					}
					// 获取文件路径
					int num = url.indexOf("//") + 2;
					num = url.indexOf("/", num);// http://后第一个/的索引值
					//			num = url.indexOf("/", num + 1);
					if(url.lastIndexOf("/")==num) {
						//http://后只有1个/
						path = downloadurl;
					}else {
						path = downloadurl +"/"+ url.substring(num + 1, url.lastIndexOf("/"));//url.substring(num + 1, url.lastIndexOf("/")第一个到最后一个之间的
					}
					File file = new File(path);

					// 如果文件夹不存在则新建
					if (!file.exists()) {
						file.mkdirs();
					}
					//判断连接是否要下载
					DataResponse dataResponse = this.downLoadJS(url, path,filename1);
				}
				log.info("static/public的静态资源不需要下载完成");
			}else {
				log.info("static/public的静态资源不需要下载");
			}


			//======================================================================================条款协议下载=================================
			boolean downflagTK=compareTiaoKuan(stringListURL,req.getSystemCode(),req.getVersion());

			if (downflagTK) {
				//下载调款协议
				log.info("条款协议更新了，需要下载");
				for (int i = 0; i < stringListURL.size(); i++){
					String path = "";
					String url = stringListURL.get(i);
					if(!isURL(url)) {
						continue;
					}
					if (!url.contains("/image/instructions/")&&sdflag){
						continue;
					}


					//处理长字符串；处理非截图的静态url
					if (!url.contains("/api/commom/image/querypicture") && url.indexOf("?")>-1 ) {
						url = url.substring(0, url.indexOf("?"));
					}
					// 获取文件名称
					String filename1 = url.substring(url.lastIndexOf("/") + 1);
					if(!url.contains("/api/commom/image/querypicture") && filename1.indexOf("?")>-1) {
						filename1 = filename1.substring(0,filename1.indexOf("?"));
					}
					if (url.contains("/api/commom/image/querypicture")) {
						//地址需要将？和 = 替换成/
						filename1=filename1.replaceAll("[?,=]", "_");
					}

					// 获取文件路径
					int num = url.indexOf("//") + 2;
					num = url.indexOf("/", num);// http://后第一个/的索引值
					//			num = url.indexOf("/", num + 1);
					if(url.lastIndexOf("/")==num) {
						//http://后只有1个/
						path = downloadurl;
					}else {
						path = downloadurl +"/"+ url.substring(num + 1, url.lastIndexOf("/"));//url.substring(num + 1, url.lastIndexOf("/")第一个到最后一个之间的
					}
					File file = new File(path);

					// 如果文件夹不存在则新建
					if (!file.exists()) {
						file.mkdirs();
					}
					//判断连接是否要下载
					DataResponse dataResponse = this.downLoadJS(url, path,filename1);
				}
				log.info("条款协议下载完成");
			}else{
				//不炫耀下载条款协议
				log.info("条款协议更新了，不需要下载");
			}
		} catch (Exception e) {
			log.info("获取zip包的修改时间失败====");
		}
		try {
			if (comunzipFlag) {
				log.info("----------------CollectDatServiceImpl----------------unZipStatic-------公共目录解压静开始");
				File comFile=new File(CollectDataServiceImpl.commonzippath);
				File[] files = comFile.listFiles();
				for (File file1 : files) {
					unZipFiles(file1,downloadurl+"/6.0Web");
				}
				log.info("----------------CollectDatServiceImpl----------------unZipStatic-------公共目录解压静结束");
			}
			if(unzipFlag){
				log.info("----------------CollectDatServiceImpl----------------unZipStatic-------解压静态资源开始");
				File file = new File(fileurl);
				File[] files = file.listFiles();
				for (File file1 : files) {
					unZipFiles(file1,downloadurl+"/6.0Web");
				}
				log.info("----------------CollectDatServiceImpl----------------unZipStatic-------解压静态资源结束");
			}
		} catch (Exception e) {
			log.info("zip包解压异常");
		}
}


	private String getZipName(String zipPath, String zipEntryName) {
		File saveFile=new File(zipPath);
		try {
			ZipFile zip = new ZipFile(saveFile, Charset.forName("GBK"));
			Enumeration<? extends ZipEntry> entries = zip.entries();
			if(entries.hasMoreElements()){
				ZipEntry entry = (ZipEntry) entries.nextElement();
				//entry.getName()获取文件相对zip包的路径
				zipEntryName = entry.getName();
			}

		} catch (IOException e) {

		}
		return zipEntryName;
	}
	/**
	 * 判断条款协议链接是否需要下载
	 * @param stringListURL
	 * @param sysCode
	 * @param version
	 * @return
	 */
//	private boolean compareDownloadStaticLine(List<String> stringListURL,String sysCode,String version) {
	public boolean compareDownloadStaticLine(List<String> stringListURL,String sysCode,String version) {
		if (stringListURL==null||stringListURL.size()==0) {
			//不下载
			log.info("static/public静态资源不用下载");
			return false;
		}
		for (String jsUrl : stringListURL) {
			if(jsUrl==null||jsUrl.trim().length()<=0) {
				continue;
			}
			if(!isURL(jsUrl)) {
				continue;
			}
			String sdurl=jsUrl;
			//只判断static/public含这个链接是否要下载
			if (!sdurl.contains("static/public")&&sdflag){
				continue;
			}
			if (!sdurl.contains("/api/commom/image/querypicture") && sdurl.indexOf("?")>-1 ) {
				sdurl = sdurl.substring(0, sdurl.indexOf("?"));
			}
			//替换内网连接
			if (sdurl.contains("static/public")&&sdflag){
				jsUrl=sdurl;
				jsUrl = CollectDataServiceImpl.staticresource + jsUrl.substring(jsUrl.indexOf("static/public")+"static".length());
			}


			DataResponse resp = this.connectState(jsUrl);//====
			if(ResponseStatusEnum.FAIL_CODE.getCode().equals(resp.getCode())) {
				//替换内网了，不能访问的不用下载
				continue;
			}

			SysMaintainVersionUrl newversionUrl = compareVersion(null, jsUrl);
			String tempurl=jsUrl;
			if(tempurl.indexOf("?")>-1){
				tempurl=tempurl.substring(0,tempurl.indexOf("?"));
			}
			String utilStr = redisUtil.getStr(tempurl);
			boolean equals = Objects.equals(utilStr, newversionUrl.getLastModified().replaceAll("\\s*", ""));
			if(!equals){
				log.info("static/public里面redis的key:"+tempurl);
				log.info("static/public里面redis的value:"+utilStr);
				log.info("static/public里面lastmodified:"+newversionUrl.getLastModified().replaceAll("\\s*", ""));
				redisUtil.setStr(tempurl,newversionUrl.getLastModified().replaceAll("\\s*", ""));
				redisUtil.setExpire(tempurl,1000*60*60*24*45);//key保存45天
				return true;
			}
		}
		return false;
	}

//compareTiaoKuan

	public boolean compareTiaoKuan(List<String> stringListURL,String sysCode,String version) {
		if (stringListURL==null||stringListURL.size()==0) {
			//不下载
			log.info("条款协议不需要下载");
			return false;
		}
		for (String jsUrl : stringListURL) {
			if(jsUrl==null||jsUrl.trim().length()<=0) {
				continue;
			}
			if(!isURL(jsUrl)) {
				continue;
			}
			String sdurl=jsUrl;
			if (!sdurl.contains("/image/instructions/")&&sdflag){
				continue;
			}
			if (!sdurl.contains("/api/commom/image/querypicture") && sdurl.indexOf("?")>-1 ) {
				sdurl = sdurl.substring(0, sdurl.indexOf("?"));
			}
			//替换内网
			if (sdurl.contains("/image/instructions/")&&sdflag){
				jsUrl=sdurl;
				jsUrl = ebankimage + jsUrl.substring(jsUrl.indexOf("/image/instructions/"), jsUrl.length());//生产上处理逻辑
			}

			DataResponse resp = this.connectState(jsUrl);//====
			if(ResponseStatusEnum.FAIL_CODE.getCode().equals(resp.getCode())) {
				continue;
			}
			SysMaintainVersionUrl newversionUrl = compareVersion(null, jsUrl);
			//资源服务器上存在的地方
			String downloadurl = filePath + sysCode + "/" + version ;
			String path=jsUrl.replace(ebankimage,downloadurl);
			//文件名
			String tempRoute = path.substring(0, path.lastIndexOf("/") + 1);
			String filename=path.substring(path.lastIndexOf("/") + 1,path.length());
			if(sdurl.contains("/image/instructions/")&&sdflag){
				String realPath=tempRoute+newversionUrl.getLastModified().replaceAll("\\s*", "")+"/"+filename;
//				System.out.println("文件保存地址："+realPath);
				File file =new File(realPath);
				if (!file.exists()) {
					log.info("需要下载的条款协议外网链接："+sdurl);
					log.info("需要下载的条款协议内网链接："+jsUrl);
					log.info("需要下载的条款协议文件保存地址："+realPath);
					return true;
				}
			}
		}

		return false;
	}


























	static String loadStream(InputStream in) throws IOException
	{
		int ptr = 0;
		in = new BufferedInputStream(in);
		StringBuffer buffer = new StringBuffer();
		while ((ptr = in.read()) != -1)
		{
			buffer.append((char) ptr);
		}
		return buffer.toString();

	}

	public static void unZipFiles(String zipPath, String descDir) throws IOException {
		unZipFiles(new File(zipPath), descDir);
	}

	/**
	 * 解压文件到指定目录
	 * 解压后的文件名，和之前一致
	 * @param zipFile   待解压的zip文件
	 * @param descDir   指定目录
	 */
	@SuppressWarnings("rawtypes")
	public static void unZipFiles(File zipFile, String descDir) throws IOException {

		ZipFile zip = new ZipFile(zipFile, Charset.forName("GBK"));//解决中文文件夹乱码
		String name = zip.getName().substring(zip.getName().lastIndexOf('/')+1, zip.getName().lastIndexOf('.'));

		log.info("zip包的名字"+name);

		File pathFile = new File(descDir);
		if (!pathFile.exists()) {
			pathFile.mkdirs();
		}

		for (Enumeration<? extends ZipEntry> entries = zip.entries(); entries.hasMoreElements();) {
			ZipEntry entry = (ZipEntry) entries.nextElement();
			//entry.getName()获取文件相对zip包的路径
			String zipEntryName = entry.getName();
			log.info("zipEntryName： "+zipEntryName);
			InputStream in = zip.getInputStream(entry);
			String outPath = (descDir +"/"+ zipEntryName).replaceAll("\\*", "/");

			// 判断路径是否存在,不存在则创建文件路径
			File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
			if (!file.exists()) {
				file.mkdirs();
			}
			// 判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
			if (new File(outPath).isDirectory()) {
				continue;
			}
			// 输出文件路径信息
//          System.out.println(outPath);

			FileOutputStream out = new FileOutputStream(outPath);
			byte[] buf1 = new byte[1024];
			int len;
			while ((len = in.read(buf1)) > 0) {
				out.write(buf1, 0, len);
			}

			out.close();
			in.close();
		}
		System.out.println("******************解压完毕********************");
		return;
	}
	
	

    /**
     * 更据错误的id集合，错误回退
     * @param idList
     */
	private String fileDir ="/data/work/appdata/video/";
	public void deleteFailData(List<String> idList){
		if (idList==null||idList.size()==0) {
			log.info("collectDataServiceImpl的deleteFailData方法入参不对");
			return;
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");

        List<DataCollect> dataCollects=dataCollectMapper.queryDataByIdList(idList);
		log.info("collectDataServiceImpl的deleteFailData方法开始");
		//清视频数据redis
		RedisTemplate<String, String>template = redisUtil.getStrRedisTemplate();
		ZSetOperations<String, String> opsForZSet = template.opsForZSet();
		for (String id : idList) {
			Set<String> zset = opsForZSet.range("v2"+"video"+id, 0, -1);
			for (String s : zset) {
				//删除值
				opsForZSet.remove(id,s);
			}
			//删除键
			redisUtil.delete(id);
		}
		log.info("collectDataServiceImpl的deleteFailData方法---上传失败，删除redis数据结束");
		//删除txt视频文件
//		List<DataCollect> dataCollects=dataCollectMapper.queryDataByIdList(idList);
		if(dataCollects!=null&&dataCollects.size()>0){
			for (DataCollect dataCollect : dataCollects) {
				String nowDateStr = "";
				if (dataCollect != null && dataCollect.getUploadTime() != null) {
					nowDateStr = sdf.format(dataCollect.getUploadTime());
				} else {
					nowDateStr = sdf.format(new Date());
				}

//				String filePath = fileDir;
				String filePath = fileDir;
				filePath = String.valueOf(filePath) + nowDateStr.substring(0, 4)
						+ "/" + nowDateStr.substring(4, 6) + "/"
						+ nowDateStr.substring(6, 8) + "/" + dataCollect.getId()
						+ "/";
				String fileName = String.valueOf(dataCollect.getId()) + nowDateStr
						+ ".txt";
				String path =  filePath+ fileName;
				//数据库如果存了视频路径，以数据库为准
				if (dataCollect.getUploadUrl() != null
						&& dataCollect.getUploadUrl().trim().length() > 0) {
					path = dataCollect.getUploadUrl();
				}
				File file=new File(path);
				if (forceDelete(file)) {
					log.info("collectDataServiceImpl的deleteFailData方法---上传失败，删除视频"+fileName+"删除成功");
				}
			}
		}
		log.info("collectDataServiceImpl的deleteFailData方法---上传失败，删除视频TXT数据结束");

        //删除业务数据deleteZipFail
        log.info("collectDataServiceImpl的deleteFailData方法入参"+idList);
        log.info("collectDataServiceImpl的deleteFailData方法---上传失败，删除数据库数据开始");
        deleteZipFail(idList);
        log.info("collectDataServiceImpl的deleteFailData方法---上传失败，删除数据库数据结束");

		log.info("collectDataServiceImpl的deleteFailData方法结束");

	}
//强制删除文件
	public boolean forceDelete(File file) {
		boolean result = file.delete();
		int tryCount = 0;
		while (!result && tryCount++ < 10) {
			System.gc();    //回收资源
			result = file.delete();
		}
		return result;
	}
	

}